Search code examples
matlabloopscell-array

Add the resulting array of each loop to a cell


I have some algorithm including a while loop:

 while  (condition)
    % do something and return a result array B
 end

Let's say:

 -Loop 1: B1=[1 2 3 4 5....9];
 -Loop 2: B2=[10 11 12....15]; 
 -Loop 3: B3=[16 17 18 19]   ;  
 -Loop 4: B4=[20 21 22....30]; 

How can I create a cell A={B1,B2,B3,B4} when the loop is finished?

For my real data, the while loop may be looping 100 times or more, the above is a simplification.


Solution

  • You can make use of the end keyword

    % Initialise empty cell array
    A = {};
    while *condition*
        % Create B using some calculation (different each loop)
        B = [1 2 3];
        % Other code ...
        % Assign to array
        A{end+1} = B;
    end