Changing variable name in loop

前端 未结 2 1134

This is in continuation to my question Extract matrix from existing matrix Now I am separating these matrices by the code (Not correct !)

相关标签:
2条回答
  • 2020-12-07 04:20

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

    0 讨论(0)
  • 2020-12-07 04:27

    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
    
    0 讨论(0)
提交回复
热议问题