How can I add number after char and define as a variable
9 Ansichten (letzte 30 Tage)
Ältere Kommentare anzeigen
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 Kommentar
Antworten (3)
Ingrid
am 26 Mai 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 Kommentar
Stephen23
am 26 Mai 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.
Jan
am 26 Mai 2015
Bearbeitet: Jan
am 26 Mai 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.
0 Kommentare
Siehe auch
Kategorien
Mehr zu Variables finden Sie in Help Center und File Exchange
Produkte
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!