-2

My code is something like:

for i=1:n
   a=something;
   b=something;

   c=cell(n,1);
   c{i,1}=[a b];
end

Where a and b are both a 1x3 matrix. When I execute the loop Matlab saves only the result of the last iteration in the last cell. What am I doing wrong? Because if I remove the preallocation it works, but stores the results in a 1xn cell array, while I would like them in a nx1 cell array. P.S. If there is a more efficient/fast way of doing something like this instead of using a for loop the solution would be very welcome.

  • 3
    You recreate your cell array c each time in the loop. you could have find out by debugging and looking what `c=cell(n,1);` is doing. Why not just moving the initialization outside of the loop? – NoDataDumpNoContribution Jul 21 '15 at 13:55

1 Answers1

1

Move the preallocation of the cell array outside the loop:

c=cell(n,1);
for i=1:n
   a=something;
   b=something;

   c{i,1}=[a b];
end

The way you have it, you're overwriting the contents of what you've saved on every loop iteration.

David Kelley
  • 1,418
  • 3
  • 21
  • 35