Search code examples
matlabfor-loopcell-array

Why Matlab does not save the partial results of my loop in a cell array?


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.


Solution

  • 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.