Change variable name in a loop
125 次查看(过去 30 天)
显示 更早的评论
Hi,
I have a problem with naming a variable during a for loop. I want to change the variable name in each iteration, so I use eval function for naming like this
dataset=rand(3);
for i=1:N
eval(['NAME_' num2str(i) '=dataset']);
end
But with eval function I always have out put on command window. Does anyone knows better solution for naming or not to show the output of eval function?
Thanks,
2 个评论
采纳的回答
Walter Roberson
2012-6-4
2 个评论
Joseph Cheng
2014-9-4
编辑:Joseph Cheng
2014-9-4
In addition to Walter's post you could go:
dataset=rand(3);
for i=1:N
Name{i} =dataset;
end
Which is equivalent to your Name_# variable. Instead of working with Name_# you would type Name{#} instead. Note the {} bracket type as these are cells. Using cells also give the ability to have different sizes of dataset. Also with the Name{#} convention you do not have to hard code or use eval again to reprocess the data. For instance if there needs to be a scaling of all the data in Name you would have to hard code Name_1*2, Name_2*2, etc. you could write a for loop to do it and without using eval.
更多回答(1 个)
Sirshendu Mondal
2020-5-4
Instead of
eval(['NAME_' num2str(i) '=dataset']);
use
eval(['NAME_' num2str(i) '=dataset;']);
5 个评论
David Valentine
2022-11-22
Thank you so much for this anwer(and the querier for that matter)! I'm working on a project that needed something like this, and all I could find was people saying to make either a structure or double array.
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Matrix Indexing 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!