How can I add number after char and define as a variable
조회 수: 9 (최근 30일)
이전 댓글 표시
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
답변 (3개)
Ingrid
2015년 5월 26일
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
Stephen23
2015년 5월 26일
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
2015년 5월 26일
편집: Jan
2015년 5월 26일
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
참고 항목
제품
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!