Creating a new variable in each iteration...

11 ビュー (過去 30 日間)
Doron
Doron 2012 年 2 月 20 日
編集済み: Stephen23 2019 年 6 月 19 日
I want to create a new variable in each iteration of a for loop... x_1, x_2, x_3, etc... up to x_50
count = 0;
for i = 2:2:100
count = count + 1;
x_(...I want "count" to go in here... what is the code to achieve this?...) = i^2
end
Basically, there should be an x_1 = 4 created in the first iteration, x_2 = 16 in the second iteration, etc... up to x_50 = 10000
Thanks
D Howard
Note: I have seen others ask similar questions, with experienced users saying things like "this is a bad idea because it is hard to reference these later..." and they suggest creating a vector, but my problem is more general and this is not an option.

採用された回答

James Tursa
James Tursa 2012 年 2 月 20 日
E.g., with the usual caveats about this typically being a bad idea:
eval(['x_' num2str(count) ' = i^2']);
  11 件のコメント
Jiro Doke
Jiro Doke 2012 年 2 月 20 日
Oh I see. Right, you don't want to do that. If you have P already and want to break it up, you should create a different cell array with a different name. Actually, it probably won't let you create it and give you an error.
You may also want to take a look at the function "mat2cell", that allows you to take a regular matrix P and convert to a cell array.
Doron
Doron 2012 年 2 月 20 日
Ok Jiro, I am about to ask post question directly related to this...
...This is going somewhere, believe me.
Doron

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

その他の回答 (1 件)

Walter Roberson
Walter Roberson 2012 年 2 月 20 日
As best I recall at the moment, I have not had a need for dynamic variable names since the days I programmed in REXX ... 25 years ago.
  1 件のコメント
Doron
Doron 2012 年 2 月 20 日
Hello Walter,
Thank you for this link. I saw that you commented on my original posting (my other question) on plotting from a matrix... there was some confusion about what I want to do.
I rewrote the question to a specific example, you assistance would be greatly appreciated.
D Howard

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

カテゴリ

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