How can I add number after char and define as a variable

Hello,
I defined A as a vector
A = [1,2,3,4,5];
I want to add the elements after 'r' letter and create another vector
For example
A(1) = r1
A(2) = r2
.
.
.
Also when I enter 'r1' on the command window, I want to see r1 = 1.
How can I do these
Thanks.

1 comentario

Stephen23
Stephen23 el 26 de Mayo de 2015
Editada: Stephen23 el 26 de Mayo de 2015
Do not do this. It is poor programming style, and should be avoided. Do not use eval for such trivial functionality. Read the answers to know why.

Iniciar sesión para comentar.

Respuestas (3)

you could use the eval function for this but it is not recommended to do this (search the Internet for why)
You could use something like the following:
A = [1,2,3,4,5];
A new vector B with the r concatenated in front:
for ii = 1:length(A)
B{ii,1} = sprintf('r%1.0f',A(ii));
end
if you really want to see r1=1 if you type r1, than this can only be done by the eval function by my knowledge since this can only be done when you name the variable r1 etcetera instead of B as was done here but this is not recommended.
if you just want to see r1=1 by any means (and not after typing r1) you could use fprinf
for ii = 1:length(B)
fprintf('%s=%1.0f\n',B{ii},A(ii))
end

1 comentario

Avoid using eval for such trivial operations like allocating to variables. Instead it you should use more robust and faster methods like putting your data in numeric arrays, cell arrays or structures.

Iniciar sesión para comentar.

Jan
Jan el 26 de Mayo de 2015
Editada: Jan el 26 de Mayo de 2015
Don't do it. Programming techniques, which use the hiding of indices in the names of variables, are known to increase the level of complexity of the code without any benefits. See: FAQ: How to create the variables A1, A2, A3, ...
Using "A(1)" is much smarter and more efficient then creating a variable "r1" dynamically. Note that this topic is discussed daily in this forum.

Categorías

Más información sobre Variables en Centro de ayuda y File Exchange.

Productos

Preguntada:

el 26 de Mayo de 2015

Respondida:

el 26 de Mayo de 2015

Community Treasure Hunt

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

Start Hunting!

Translated by