String in variable using a for loop
2 visualizaciones (últimos 30 días)
Mostrar comentarios más antiguos
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 comentario
Stephen23
el 9 de Mayo de 2017
Editada: Stephen23
el 9 de Mayo de 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:
Respuestas (1)
Ver también
Categorías
Más información sobre Loops and Conditional Statements en Help Center y File Exchange.
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!