How can use a for loop to name a matrix?

23 views (last 30 days)
After each iteration of my for loop, a matrix is produced. I want to name that matrix based on the number of the iteration. This is what I have so far:
for trials = 1:max_trials
a = int2str(trials);
a = output_matrix;
However, Matlab just stores the last matrix produced under the variable 'a'. How can I get it to store each matrix under its respective iteration? For example, if max_trials = 3, how would I get three separate matrices labelled '1', '2' and '3'?
Thank you!
  1 Comment
Asghar Molaei
Asghar Molaei on 15 May 2021
Thank you very much for asking this question. It was my question too.

Sign in to comment.

Accepted Answer

Stephen23
Stephen23 on 27 Mar 2015
Edited: Stephen23 on 12 Sep 2023
Use a cell array like this:
out = cell(1,max_trials);
for trial = 1:max_trials
out{trial} = ... your calculation here
end
Avoid creating dynamically named variables:

More Answers (1)

David Young
David Young on 27 Mar 2015
One way is to use a cell array, like this
for trials = 1:max_trials
< compute result, assign to a >
output_matrix{trials} = a;
end
Then output_matrix{k} is the value of the a matrix for iteration k.
Don't try to assign the result of each iteration to a different variable by constructing different names inside the loop - it's a very bad way to do it.
  1 Comment
David Young
David Young on 27 Mar 2015
... as Stephen Cobeldick explains in more detail in his answer.

Sign in to comment.

Categories

Find more on Loops and Conditional Statements in Help Center and File Exchange

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!