0

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.

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks, this seemed to do what I wanted it to.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.