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

34 views (last 30 days)
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 Comment
Stephen23
Stephen23 on 26 May 2015
Edited: Stephen23 on 26 May 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.

Sign in to comment.

Answers (3)

Ingrid
Ingrid on 26 May 2015
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 Comment
Stephen23
Stephen23 on 26 May 2015
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.

Sign in to comment.


Jan
Jan on 26 May 2015
Edited: Jan on 26 May 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.

Beycan Ibrahimoglu
Beycan Ibrahimoglu on 26 May 2015
Ok, thanks to everyone

Community Treasure Hunt

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

Start Hunting!