for loop for variables

23 ビュー (過去 30 日間)
Nachiket Patki
Nachiket Patki 2016 年 5 月 9 日
編集済み: Stephen23 2023 年 9 月 12 日
I have written one code as follows,
for i=1:10
Ai=i;
fprintf('A is: %d \n',Ai)
end
what i want to achieve from here is, I want to store 1,2,3..10 in variables A1,A2,A3...A10. But the code i have created is giving me Ai as variable instead A1,A2...etc and storing Ai=10 at the end.(It has also created row vector A=[1:10])

採用された回答

Azzi Abdelmalek
Azzi Abdelmalek 2016 年 5 月 9 日
編集済み: Azzi Abdelmalek 2016 年 5 月 9 日
It's not a good idea to create variables A1,A2, ..., An. The array A=1:10 contains all your data. Why to create 10 variables, when one variable is sufficient
  1 件のコメント
Nachiket Patki
Nachiket Patki 2016 年 5 月 9 日
編集済み: Nachiket Patki 2016 年 5 月 9 日
Actually sir I wanted to do the operations on each of them separately that's why i want to store them at different variables.

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

その他の回答 (1 件)

Weird Rando
Weird Rando 2016 年 5 月 9 日
@Stephen: Haha I read the same thing somewhere online. But that didn't stop me :3
for i=1:10
eval(sprintf('A%i = i',i))
end
  3 件のコメント
Stephen23
Stephen23 2016 年 5 月 9 日
編集済み: Stephen23 2023 年 9 月 12 日
@Scott: this is how it often goes:
  • beginner: I have a great idea!
  • experienced user: what?
  • b. I will access my variables dynamically!
  • e. Don't do that, it is inefficient, complex, buggy, and hard to debug. Here is why...
  • b. No! I am really cunning, and I know more than every experienced user who is advising me to use better, more reliable methods! I even know better than TMW, who wrote a whole page about avoiding dynamic variable names.
  • e. Here are some better ways to...
  • b. I am so great, it works!!!
  • e. sigh.
Three years later:
  • slightly-more-experienced beginner: damn, I have to rewrite all of this awful, slow, buggy code that I wrote! And I have to unlearn all these bad habits!
Weird Rando
Weird Rando 2016 年 5 月 10 日
It been three years, and yeah that did happen. Can't even understand what I code.

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

カテゴリ

Help Center および File ExchangeWhos についてさらに検索

タグ

Community Treasure Hunt

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

Start Hunting!

Translated by