noufal
noufal

Reputation: 970

Changing variable name in loop

This is in continuation to my question Extract matrix from existing matrix Now I am separating these matrices by the 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 accordingly, like

mat1
mat2
mat3
mat4

Can anybody suggest an easy method to it?

Upvotes: 3

Views: 5949

Answers (2)

Shai
Shai

Reputation: 114976

Following @Jonas and @Clement-J.'s proposals, here is how toy use cells and structs:

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

Nice thing about the struct (with variable field names) is that you can save it

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

and you'll have variables mat1,...,mat10 in the mat-file! Cool!

Some good coding practices:

  1. Pre-allocate matrices and arrays in Matlab. Changing a variable size inside a loop really slows down Matlab.

  2. Do not use i and j as loop variables (or as variables at all) since they are used as sqrt(-1) by Matlab.

  3. Why having variables with variable names? You need to have an extremely good reason for doing this! Please describe what you are trying to achieve, and I'm sure you'll get better and more elegant solutions here...

Upvotes: 10

Karthik V
Karthik V

Reputation: 1897

Here is a way to do it using the eval and sprintf functions. See documentation for both to learn more about them.

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

Upvotes: 3

Related Questions