String in variable using a for loop

조회 수: 2 (최근 30일)
Steve Yianni
Steve Yianni 2017년 5월 9일
편집: Stephen23 2017년 5월 9일
Hi all,
How would I make a new variable in a for loop with a string, as the variable name?
Such that
x=
[0.3750
4.1250
3.7465];
for i = 1:3
strcat('xCentre_', num2str(i)) = x(i,:);
end
such that
xCentre_1 = 0.3750
xCentre_2 = 4.1250
xCentre_3 = 3.7465
  댓글 수: 1
Stephen23
Stephen23 2017년 5월 9일
편집: Stephen23 2017년 5월 9일
When you create variable names like this:
xCentre_1
xCentre_2
xCentre_3
then you are putting a pseudo-index into the variable name. This will be slow, buggy, hard to debug, obfuscated and ugly. Much simpler is to turn that pseudo-index into a real index, because real indices are fast, efficient, easy to read, easy to debug, and show the intent of your code.
xCentre(1) = ...
xCentre(2) = ...
xCentre(3) = ...
and once you decide to use real indices, then looping over them is easy too (because that is exactly what indices are intended for):
for k = 1:numel(x)
xCentre(k) = x(k);
end
although in your case, because you simply allocate the values without any change, this could be simplified even more to just:
xCentre = x;
Did you see what I did there? By getting rid of a bad code design decision, I made the code much much simpler. You can do that too!
PS: putting any kind of meta-data into variable names will make for slow, buggy, obfuscated, hard to debug code. See this tutorial for more information on why:

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

답변 (1개)

Walter Roberson
Walter Roberson 2017년 5월 9일

카테고리

Help CenterFile Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by