How to generate different variables to store different sets of matrix?

Using for loop, 35 different matrices are generated in my codes. How can I generate 35 different variables to store them respectively?

 Accepted Answer

Just DON’T!
Create a multidimensional matrix, or if your matrices are different sizes, use a cell array.

4 Comments

Sorry, I am still a rookie in matlab... How to Create a multidimensional matrix? All the generated matrices are of same size.
No need to apologise! It’s just that creating multiple variables that could be combined together in one variable as a multidimensional matrix or cell array raises hackles here.
This is how I would do it:
M = nan(3,3,3); % Preallocate
for k1 = 1:3
M(:,:,k1) = randi(10*k1,3,3);
end
The preallocation step declares a contiguous area of memory so the loop doesn’t have to create new memory locations at each iteration, slowing down the calculation. The first two dimensions of the ‘M’ array are those of each individual matrix, and the last is the additional dimension that stores each matrix in ‘M’. You would refer to them later in your code the same way. You can watch the process in this example by removing the semicolon at the end. I kept the arrays small for that reason.
Thanks man, my problem is resolved!
My pleasure!
If you want to call the matrix created at iteration 20 of the loop, you can refer to it as:
M(:,:,20)
However if you want to do calculations with it, it’s sometimes easier to create a separate temporary matrix for it, for instance:
Mt = M(:,:,20);
to avoid having to write all the subscripts each time you use it in your calculations.

Sign in to comment.

More Answers (0)

Tags

Community Treasure Hunt

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

Start Hunting!