MATLAB: Indexing or appending numerical variables

MATLAB: Indexing or appending numerical variables


I have many matrix variables like G1, G2… I want to create a loop that new variables chance their name. For example,
for i=1:32 in first step when i=1 >> M=G1 second step when i=2 >> M=G2 … and so on.
How can I make “i” recognizable for G matrices?

Best Answer

  • You can do that using the eval function, and this seems a valid use for it. I would create ‘M’ as a cell array, and then assign elements of ‘M’ in a loop.
    N = ...; % Number Of Matrices
    for k = 1:N
    M{k} = eval(sprintf('G%d', k));
    You can then address individual elements of ‘M’ in the rest of your code. See the documentation on Cell Arrays for details on how to use them if you are not familiar with them.
    NOTE This is UNTESTED CODE. It should work, probably with modifications.
  • Add a Comment

    Your email address will not be published. Required fields are marked *