How to use the string of a variable as a new variable name?

29 vues (au cours des 30 derniers jours)
Jocelyne Beelen
Jocelyne Beelen le 27 Juil 2016
Modifié(e) : Stephen23 le 25 Juin 2019
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 commentaires
Jocelyne Beelen
Jocelyne Beelen le 27 Juil 2016
My issue is that I cannot store MR_0011 (which is a structure) in an array/table. So how would i use indexing in this situation? can you provide me with an example?
Stephen23
Stephen23 le 27 Juil 2016
Modifié(e) : Stephen23 le 27 Juil 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)...

Connectez-vous pour commenter.

Réponses (2)

Adam
Adam le 27 Juil 2016
Modifié(e) : Adam le 27 Juil 2016
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'),

Stephen23
Stephen23 le 27 Juil 2016
Modifié(e) : Stephen23 le 25 Juin 2019

Catégories

En savoir plus sur Structures dans Help Center et File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by