I have a very basic question. I want to write a loop in MATLAB which creates 4 separate variables with "a" number "in the name" and put 22 in each of them. Something like this:
for a=1:4
star'{a}'=22
end
But this does not seem to identify "a" separately and not as a part of the variable name. How should I use syntax to do that?

 Respuesta aceptada

Adam Danz
Adam Danz el 14 de Abr. de 2020
Editada: Adam Danz el 14 de Abr. de 2020

1 voto

What you're describing is called dynamic variable naming and it should be avoided. Instead, you can store the intended variable name and its value in a cell array as shown below.
star = cell(4,2);
for a=1:4
star{a,1} = 'a'; % in reality, this would vary across iterations
star{a,2} = 22; % in reality, this would vary across iterations
end
Or, you could store it in a structure,
star = struct();
for a=1:4
star.('a') = 22; % assuming 'a' and will vary across iterations
end
See this outline for reasons to avoid using dynamic variable names.

5 comentarios

Adam Danz
Adam Danz el 14 de Abr. de 2020
Shokufeh Sadaghiani's answer moved here as a comment.
Thanks, this perfectly works for this example, but what I actually want to do is to save 4 NIFTI files with names: e1-e4 as variables: e1-e4 and I want to do that with a loop. Is that possibe? Or is there a better way for doing that?
Adam Danz
Adam Danz el 14 de Abr. de 2020
Editada: Adam Danz el 14 de Abr. de 2020
Perhaps this example will help, showing how to change the description field of a NIFTI file.
The 'a' in either of my demos can be changed to anything you want.
Example:
sprintf('e%d',1)
Stephen23
Stephen23 el 14 de Abr. de 2020
"...I actually want to do is to save 4 NIFTI files with names: e1-e4 as variables: e1-e4 and I want to do that with a loop. Is that possibe?"
It is certainly possible, but only if you want to force yourself into writing slow, complex, obfuscated, buggy code that is hard to debug. Read this to know why: https://www.mathworks.com/matlabcentral/answers/304528-tutorial-why-variables-should-not-be-named-dynamically-eval
"Or is there a better way for doing that?"
Yes, you use indexing just like Adam Danz's answer shows, or the MATLAB documentation shows:
Shokufeh Sadaghiani
Shokufeh Sadaghiani el 14 de Abr. de 2020
I am new to MATLAB and coding. Thank you both.
Adam Danz
Adam Danz el 14 de Abr. de 2020
The use of dynamic variable names is common for newbies and it's good you learned not to use them early on.

Iniciar sesión para comentar.

Más respuestas (0)

Categorías

Preguntada:

el 14 de Abr. de 2020

Comentada:

el 14 de Abr. de 2020

Community Treasure Hunt

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

Start Hunting!

Translated by