Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 204
noufal Avatar asked Jul 19 '26 15:07

noufal


2 Answers

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...

like image 170
Shai Avatar answered Jul 21 '26 20:07

Shai


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
like image 24
Karthik V Avatar answered Jul 21 '26 22:07

Karthik V



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!