3

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?

2
  • 2
    In most cases when you need something like that it's better to use cells. Commented Jan 19, 2013 at 18:24
  • 6
    Learn to use struct or cell - your approach leads you to writing very bad code. Commented Jan 19, 2013 at 18:32

2 Answers 2

10

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

Sign up to request clarification or add additional context in comments.

2 Comments

I second the opinion that using a structure to aggregate your matrices is a better idea than creating lots of separate variables. Here's a link to an article about using dynamic field references that would be great for you to read.
@tmpearce - thanks for the link - I added it into the answer!
3

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.