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 Center および File ExchangeLoops and Conditional Statements についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by