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?

 Accepted Answer

Adam Danz
Adam Danz on 14 Apr 2020
Edited: Adam Danz on 14 Apr 2020
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 Comments

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?
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)
"...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:
I am new to MATLAB and coding. Thank you both.
The use of dynamic variable names is common for newbies and it's good you learned not to use them early on.

Sign in to comment.

More Answers (0)

Community Treasure Hunt

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

Start Hunting!