How to use the string of a variable as a new variable name?
Show older comments
Hi,
I am writing a code where the name of a variable needs to change through every iteration of a for loop.
for p = 1:20
newname = strcat ('B',int2str(p));
So, after this, newname = B1 in the first iteration. Now, I want to load an image that I call B1.
How would I use this string I created in newname as a new variable name?
I want B1 = load_untouch_nii ('MR_0011.img'), but I can't figure out to have B1 be the variable name using the newname that I created.
Help please!
3 Comments
Stephen23
on 27 Jul 2016
Look at what you want to create: name1, name2, name3, etc.. Observe how the number is basically an index... and it is trivial to turn it into a real index and use a cell array, or any other kind of array.
The solution is always "use indexing", and it is NOT "lets magically make lots of variables appear in my workspace".
Especially for beginners who don't realize what slow, buggy, and obfuscated code they will write if they create variable names like that. Not to mention all of MATLAB helpful tools (you know, the ones that show you code mistakes, highlight your variables, shortcuts to function help, etc) will all stop working...
Jocelyne Beelen
on 27 Jul 2016
"I cannot store MR_0011 (which is a structure) in an array"
Yes you can. Structures are arrays, as the documentation clearly states, although you might be used to seeing them as scalar arrays... but there is no reason why you can't make it non-scalar.
Best Solution: non-scalar structure
Structures do not have to be scalar, they can be non-scalar structures. As long as your function always returns a scalar structure with the same fields, then you can simply create a non-scalar structure (using indexing, of course).
The easiest way to do this would be to simply loop over the filenames:
N = 20;
for k = N:-1:1
S(k) = load_untouch_nii(filename);
end
N = 20;
S = struct('hdr',[],'filetype',[],'fileprefix',[],'machine',[],'img',cell(1,N));
for k = 1:N
S(k) = load_untouch_nii(filename);
end
Second best: cell array
If you read my answer then you will already know about cell arrays (and non-scalar structures)...
Answers (2)
Why would you ever need the name of a variable to change during an iteration? A variable name is just a handle to the variable, its name is important for code readability but meaningless for the running of code.
In this situation you should just use an array. If your inputs are different sizes then use a cell array, else a numeric array with results concatenated will work.
B{1} = load_untouch_nii ('MR_0011.img'),
Categories
Find more on Characters and Strings in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!