Change variable name in a loop

136 visualizzazioni (ultimi 30 giorni)
Yoshihiro
Yoshihiro il 4 Giu 2012
Modificato: Stephen23 il 23 Nov 2022
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 Commenti
Stephen23
Stephen23 il 28 Giu 2018
Modificato: Stephen23 il 28 Giu 2018
JAMES WAITE
JAMES WAITE il 11 Apr 2019
@Stephen Brimhall: found your resource helpfull for my issue. Thanks!

Accedi per commentare.

Risposta accettata

Walter Roberson
Walter Roberson il 4 Giu 2012
  2 Commenti
Joseph Cheng
Joseph Cheng il 4 Set 2014
Modificato: Joseph Cheng il 4 Set 2014
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.
Byron Uzoka
Byron Uzoka il 11 Lug 2020

🤔

Accedi per commentare.

Più risposte (1)

Sirshendu Mondal
Sirshendu Mondal il 4 Mag 2020
Instead of
eval(['NAME_' num2str(i) '=dataset']);
use
eval(['NAME_' num2str(i) '=dataset;']);
  5 Commenti
David Valentine
David Valentine il 22 Nov 2022
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.
Stephen23
Stephen23 il 23 Nov 2022
Modificato: Stephen23 il 23 Nov 2022
"...all I could find was people saying to make either a structure or double array."
You can't have done very much reading on this topic if that was "all" the advice you found.
The advice given on this forum is much more nuanced and situation specific:

Accedi per commentare.

Community Treasure Hunt

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

Start Hunting!

Translated by