Search code examples
matlabmatrixcell-array

Iterate Matrix into a cell array


Is there a way I can write a for loop that will add a given number of matrix into a cell array.

`C1 = [];`

So instead of having to write everyone out like:

`cell = {}
cell = [cell C1];
cell = [cell C2];
cell = [cell C3];
cell = [cell C4];`

Where the number of C is known.


Solution

  • If the number of C matrices is known, then yes you can write a for loop to do this. At each iteration of the loop, a command string can be built and then evaluated:

    N = 4;
    cellArray = cell(N,1);  % pre-allocate memory for the array
    for i=1:N
    
        % build the command string
        cmd = ['cellArray{i} = C' num2str(i) ';'];
    
        % evaluate the string
        eval(cmd);
    
    end
    

    You could step through the code and see what cmd looks like at each iteration. Note that some developers have some concerns about using the eval command. Since you are building the command to be run at each iteration, it can make debugging (if an error should arise) somewhat more difficult.