Index with for loop variable name and definition

180 ビュー (過去 30 日間)
Stef
Stef 2018 年 6 月 28 日
編集済み: Stephen23 2018 年 6 月 29 日
I have a matrix A and avector y. I want to create a loop which names and defines them the matrix A from A1,...,A10.
for i = 1:10
A{i} = X(y==i)
end
Unfortunately this code does not work. It would be nice to end up with a double and not a cell
  1 件のコメント
Stephen23
Stephen23 2018 年 6 月 29 日
編集済み: Stephen23 2018 年 6 月 29 日
"I want to create a loop which names and defines them the matrix A from A1,...,A10."
Dynamically accessing variable names is one way that beginners force themselves into writing slow, complex buggy, code. Read this to know why:
Using a cell array with indexing is simple, neat, and very efficient. You should use a cell array with indexing.
Note that when you put a number into the variable name like that then you are using it as pseudo-indexing: note that processing pseudo-indexing is complex and slow. In contrast, real indexing of a cell array (as your question shows) is extremely fast, efficient, and easy to debug.
So far you have not provided any reason why you need to write much slower, more complex, buggier code. Cell arrays are designed to efficiently hold data arrays, exactly like you want to now.

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

採用された回答

D. Plotnick
D. Plotnick 2018 年 6 月 29 日
If I understand your question, it is parallel to the one here, which as Stephen Cobeldick points out is a bad idea.
There is sort of a way around this using a structure.
for i = 1:10
fname = ['A',num2str(i)];
B.(fname) = y(i);
end
  5 件のコメント
Stef
Stef 2018 年 6 月 29 日
Thanks, it worked!
Stephen23
Stephen23 2018 年 6 月 29 日
編集済み: Stephen23 2018 年 6 月 29 日
@Stef: note that your original code, using a cell array and indexing, is faster and simpler than this answer.
You might also find this to be of interest:

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

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeLoops and Conditional Statements についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by