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

6 次查看(过去 30 天)
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 个评论
Jocelyne Beelen
Jocelyne Beelen 2016-7-27
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 2016-7-27
编辑:Stephen23 2016-7-27
"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)...

请先登录,再进行评论。

回答(2 个)

Adam
Adam 2016-7-27
编辑:Adam 2016-7-27
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 2016-7-27
编辑:Stephen23 2019-6-25

类别

Help CenterFile Exchange 中查找有关 Characters and Strings 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by