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?

 채택된 답변

Adam Danz
Adam Danz 2020년 4월 14일
편집: Adam Danz 2020년 4월 14일

1 개 추천

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

Adam Danz
Adam Danz 2020년 4월 14일
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?
Adam Danz
Adam Danz 2020년 4월 14일
편집: Adam Danz 2020년 4월 14일
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)
Stephen23
Stephen23 2020년 4월 14일
"...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:
Shokufeh Sadaghiani
Shokufeh Sadaghiani 2020년 4월 14일
I am new to MATLAB and coding. Thank you both.
Adam Danz
Adam Danz 2020년 4월 14일
The use of dynamic variable names is common for newbies and it's good you learned not to use them early on.

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

카테고리

도움말 센터File Exchange에서 Matrix Indexing에 대해 자세히 알아보기

질문:

2020년 4월 14일

댓글:

2020년 4월 14일

Community Treasure Hunt

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

Start Hunting!

Translated by