String in variable using a for loop
2 views (last 30 days)
Show older comments
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 Comment
Stephen23
on 9 May 2017
Edited: Stephen23
on 9 May 2017
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:
See Also
Categories
Find more on Loops and Conditional Statements in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!