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

6 ビュー (過去 30 日間)
Jocelyne Beelen
Jocelyne Beelen 2016 年 7 月 27 日
編集済み: Stephen23 2019 年 6 月 25 日
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 Center および File ExchangeCharacters and Strings についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by