tags:

views:

57

answers:

1

Hey, having a wee bit of trouble. Trying to assign a variable length 1d array to different values of an array, e.g.

a(1) = [1, 0.13,0.52,0.3];
a(2) = [1, 0, .268];

However, I get the error:

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

Error in ==> lab2 at 15
a(1) = [1, 0.13,0.52,0.3];

I presume this means that it's expecting a scalar value instead of an array. Does anybody know how to assign the array to this value?

I'd rather not define it directly as a 2d array as it is for are doing solutions to different problems in a loop

Edit: Got it!

a(1,1:4) = [1, 0.13,0.52,0.3];

a(2,1:3) = [1, 0, .268];

+4  A: 

What you probably wanted to write was

a(1,:) = [1, 0.13,0.52,0.3];
a(2,:) = [1, 0, .268];

i.e the the first row is [1, 0.13,0.52,0.3] and the second row is [1, 0, .268]. This is not possible, because what would be the value of a(2,4) ?

There are two ways to fix the problem.

(1) Use cell arrays

a{1} = [1, 0.13,0.52,0.3];
a{2} = [1, 0, .268];

(2) If you know the maximum possible number of columns your solutions will have, you can preallocate your array, and write in the results like so (if you don't preallocate, you'll get zero-padding. You also risk slowing down your loop a lot, if there are many iterations, because the array will have to be recreated at every iteration.

a = NaN(nIterations,maxNumCols); %# this fills the array with not-a-numbers

tmp = [1, 0.13,0.52,0.3];
a(1,1:length(tmp)) = tmp;
tmp = [1, 0, .268];
a(2,1:length(tmp)) = tmp;
Jonas