From: Judd Foulds on
Hi,

I'm having a problem with matrices! I want to store a row vector in each row of a matrix, thus storing the information produced in the iterations of a for loop. Basic coding is:

matrix=zeros(3,3);
num=0;
for a=1:1:3,
count=0;
num=num+1;
for n=1:1:3;
count=count+1;
E=(some constants here)*n^2/3;
deltaE(count)=E;
matrix(num)=deltaE;
end

The values of n and a are different, but the iterations are the same (3 for both) which should lead to a 3x3 matrix, however, I'm getting the

In an assignment A(I) = B, the number of elements in B and
I must be the same.

If I use matrix=[matrix;deltaE] I get a vertcat error.

New to matlab and getting very tired, does anyone have any suggestions please?
thanks in advance
From: Nathan on
On Feb 20, 4:39 pm, "Judd Foulds" <georgefou...(a)googlemail.com> wrote:
> Hi,
>
> I'm having a problem with matrices! I want to store a row vector in each row of a matrix, thus storing the information produced in the iterations of a for loop. Basic coding is:
>
> matrix=zeros(3,3);
> num=0;
> for a=1:1:3,
>    count=0;
>    num=num+1;
> for n=1:1:3;
>    count=count+1;
>    E=(some constants here)*n^2/3;
>    deltaE(count)=E;
>    matrix(num)=deltaE;
> end
>
> The values of n and a are different, but the iterations are the same (3 for both) which should lead to a 3x3 matrix, however, I'm getting the
>
>  In an assignment  A(I) = B, the number of elements in B and
>  I must be the same.
>
> If I use matrix=[matrix;deltaE] I get a vertcat error.
>
> New to matlab and getting very tired, does anyone have any suggestions please?
> thanks in advance

Please give a closer example to what you want done...
Do you just want the vector, deltaE, stored in each row of "matrix"?
(Note that deltaE does not change values for each "a" iteration)

If so, you can just do something like this (without the loops)
n = 1:3;
matrix = repmat([n.^2/3],3,1);

%%%%%%%%%%
matrix =

0.3333 1.3333 3.0000
0.3333 1.3333 3.0000
0.3333 1.3333 3.0000


What exactly do you want done?

With your for loops corrected, we get the same result:
matrix=zeros(3,3);
num=0;
for a=1:1:3,
count=0;
num=num+1;
for n=1:1:3;
count=count+1;
E=n^2/3;
deltaE(count)=E;
end
matrix(num,:)=deltaE; % note the : and it being outside the inner
loop
end

-Nathan