Could I use a dynamic character or string in a for loop to call a variable with different name?

23 ビュー (過去 30 日間)
I couldn't figure out the best way to ask this question so apology for the confusing title. Let's say I had multiple variables with different name called var1,var2,var3... with values in each.
Is there a way to access each of the variable in such a way like
for k = 1:10
variable(k) = (variable%d,k)
end
So that I can access the variables with different names where %d can take on given integer similar to C language? Another way might be if there was a variable called GreenEggs&Ham and I want to access it like
A = 'GreenEggs'
B = 'Ham'
BreakFast = (%s&%s,A,B);
  2 件のコメント
Oleg Komarov
Oleg Komarov 2014 年 8 月 25 日
Avoid creating var1, ..., var# in the first place!
Stephen23
Stephen23 2015 年 3 月 11 日
編集済み: Stephen23 2023 年 9 月 12 日
Although this answer has already been accepted, avoid using eval and do not create dynamically named variables:

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

採用された回答

Andrew Reibold
Andrew Reibold 2014 年 8 月 25 日
編集済み: Andrew Reibold 2014 年 8 月 25 日
Use eval , Its really easy! Reads a string as a variable.
Here is an example. Using the base 'var', I increment the variable number and get the data from each one.
var1 = 10
var2 = 20
var3 = 50
for i = 1:3
variables(i) = eval(['var',num2str(i)])
end
  3 件のコメント
Yuki Himekawa
Yuki Himekawa 2014 年 8 月 25 日
You're right, it made my life so much easier! I can probably use it for much more applications in future too, thanks!
José-Luis
José-Luis 2014 年 8 月 25 日
Using eval is generally a bad idea and should be avoided when possible.

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

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeCharacters and Strings についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by