Assigning data to variable names in a vector during a for loop.

21 ビュー (過去 30 日間)
Mamed
Mamed 2011 年 11 月 1 日
編集済み: Stephen23 2023 年 9 月 12 日
Hi
I wanna make a vector with variable names and then assign values to the from a for loop.
Estimates = [1 2 3 4 5 6 7];
variables = (a b c d e f g};
for i = 1:length(variables)
variables(i) = Estimates(1);
end
So that
a = 1 b = 2 etc
and so on. Is this possible?
And also is i possible to make it so that you create variables named in incremental way? I.e
b = [2 5 45];
for i = 1:length(b)
'a'+int2str(i) = b(i);
end
that is
a1 = 2 a2 = 5 and a3 = 45
Kind Regards

採用された回答

Jonas Reber
Jonas Reber 2011 年 11 月 1 日
yes this is possible. you could use the command "eval" that comes with matlab. have a look at the documentation.
for your case you would have to change the variables array to have chars inside - i.e.:
vars = {'a', 'b', 'c'}
and in the for loop use
vals = [1 2 3 4]
vars = {'a', 'b', 'c', 'd'}
for i = vals
eval([vars{i} '= vals(i)'])
end
also, you might want to have a look at the "genvarname" command of matlab that does exactly what you want in the second part of your question.
  2 件のコメント
Mamed
Mamed 2011 年 11 月 1 日
Thanks a lot. Just a smal question is there a way to stop it from showing the values that are being assigned? the ; doesn't work.
Kind regards
Daniel Shub
Daniel Shub 2011 年 11 月 1 日
Just add a semicolon inside the eval
eval([vars{i} '= vals(i);'])

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

その他の回答 (1 件)

Daniel Shub
Daniel Shub 2011 年 11 月 1 日
While you can do this with eval, it is generally not recommended. This is pretty well covered in the FAQ: http://matlab.wikia.com/wiki/FAQ#How_can_I_create_variables_A1.2C_A2.2C....2CA10_in_a_loop.3F

カテゴリ

Help Center および File ExchangeMatrices and Arrays についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by