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?

 採用された回答

Star Strider
Star Strider 2017 年 1 月 3 日

0 投票

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.
Example:
N = ...; % Number Of Matrices
for k = 1:N
M{k} = eval(sprintf('G%d', k));
end
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.

5 件のコメント

Star Strider
Star Strider 2017 年 1 月 3 日
Feyza Sakil’s ‘Answer’ moved here:
I tried your code, it says: "Cell contents assignment to a non-cell array object."
Star Strider
Star Strider 2017 年 1 月 3 日
I have no idea what your ‘matrix variables’ are, since you have not described them.
Try this:
N = ...; % Number Of Matrices
for k = 1:N
M(k) = eval(sprintf('G%d', k));
end
The change replaces the curly brackets ‘{}’ with parentheses ‘()’.
CaptainS
CaptainS 2017 年 1 月 3 日
already tried.. :(
CaptainS
CaptainS 2017 年 1 月 3 日
In an assignment A(I) = B, the number of elements in B and I must be the same.
Error in eval (line 3) M(k) = eval(sprintf('G%d', k));
Star Strider
Star Strider 2017 年 1 月 3 日
I do not understand the reason my original Answer (using the cell array) did not work. It should work with numeric arrays, cell arrays, character arrays, structures and everything else I can think of.
Please save some (or all) of your ‘G1’, ‘G2’, matrices to a ‘.mat’ file, and use the ‘paperclip’ icon to upload them here. I cannot solve this without having access to at least some of them. (See the documentation on the ‘save’ function for information on creating a ‘.mat’ file with them if you have not used them before.)

サインインしてコメントする。

その他の回答 (0 件)

カテゴリ

ヘルプ センター および File ExchangeMatrix Indexing についてさらに検索

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by