Add the resulting array of each loop to a cell

自作多情 提交于 2021-02-17 05:52:09

问题


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.


回答1:


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



回答2:


You can join your arrays either using horzcat or []. Then initialize an cell and save them into that cell.

%% loop
count = 0 ;
iwant = cell([],1) ;
while .....
        count = count+1 ;
    %% let be your arrays
    B1=1:9 ;
    B2=10:15 ;
    B3=16:19 ;
    B4=20:30 ;
    %% join them into array
    B = [B1 B2 B3 B4] ;
    iwant{count} = B ;
end


来源:https://stackoverflow.com/questions/45992097/add-the-resulting-array-of-each-loop-to-a-cell

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!