Changing the name of a variable in a loop

This is a follow-up to my question Extract a matrix from an existing matrix Now I split these matrices into code (not correct!)

for i = 3:-1:0
    mat = m((sum((m == 0), 2)==i),:)
end

      

The above part is an update to my original question
I want to name it appropriately, for example

mat1
mat2
mat3
mat4

      

Can anyone suggest an easy way?

+3


source to share


2 answers


Following @Jonas and @ Clement-J. suggestions, this is how toy uses cell

and struct

s:

N = 10; % number of matrices
cell_mat = cell(1, N); % pre allocate (good practice)
for ii = 1 : 10
    cell_mat{ii} = rand( ii ); % generate some matrix for "mat"
    struct_mat.( sprintf( 'mat%d', ii ) ) = rand( ii );
end

      

The good thing about structure ( with variable field names ) is that you can do save

it

save ('myMatFile.mat', 'struct_mat', '-struct');



and you will have variables mat1

, ..., mat10

in mat

-file! Cool!

Some good coding techniques:

  • Pre-assign matrices and arrays in Matlab. Resizing the variable inside the loop really slows down Matlab.

  • Do not use i

    and j

    how to cycle variables (or variables in general), because they are used sqrt(-1)

    by Matlab.

  • Why do we need variables with variable names? You have to have an extremely good reason for this! Please describe what you are trying to achieve and I am sure you will get better and more elegant solutions here ...

+10


source


Here's how to do it using the eval

and functions sprintf

. For more information on these, see the documentation.



for count = 1:10
    eval(sprintf('mat%d = zeros(count);',count));
end

      

+3


source







All Articles