value from string ?

조회 수: 4 (최근 30일)
Ole
Ole 2017년 8월 1일
댓글: Ole 2017년 8월 1일
I would like to use vectarrow function to draw vectors:
The code below defines a function fx for the x and y coordinates (x1 x2 x3 ...) of the vectors. I am confused how to get back the numerical values of fx and fy (instead of 'x1' -> 2, 'x2' -> 4...).
x1 = 2; x2 = 4; x3 = 5; x4 = 7;
y1 = 2; y2 = 4; y3 = 5; y4 = 7;
v= [1 2 3 4]; % the order changes
vv = length(v);
fx = cell(vv, 1);
for i=1:vv
fx{i} = strcat('x', num2str(v(i)));
fy{i} = strcat('y', num2str(v(i)));
end
%plot
for j = 1:length(v)-1
vectarrow([char(fx(j)); char(fy(j))], [char(fx(j+1)); char(fy(j+1))]); % does not work
hold on
end
hold off
  댓글 수: 3
Stephen23
Stephen23 2017년 8월 1일
편집: Stephen23 2017년 8월 1일
@Ole: all of the vectarrow examples show it being call with numeric inputs arguments. Why are you calling vectarrow with character input arguments?
Ole
Ole 2017년 8월 1일
편집: Ole 2017년 8월 1일
I dont know how to get the numerical value. fx(1) is 'x1', x1 is defined as 2. I tried str2double(fx(1)) and it gives NaN. str2num(char(fx(1))) gives []. thanks

댓글을 달려면 로그인하십시오.

채택된 답변

Stephen23
Stephen23 2017년 8월 1일
편집: Stephen23 2017년 8월 1일
@Ole: putting your values into lots of separately named variables called x1, and x2, etc, is a really bad way to write code. You have just found out one reason why. Read these to know some other reasons:
and a thousand other times that this has been thoroughly discussed.
Consider what the MATLAB documentation says about your idea: "A frequent use of the eval function is to create sets of variables such as A1, A2, ..., An, but this approach does not use the array processing power of MATLAB and is not recommended."
Your code will be much simpler and more efficient when you simply put that data into vectors, and loop over the elements of the vectors. The name "MATLAB" comes from "MATrix LABoratory", and not from "Lets put all of the values into lots of separate variables and make the code really complicated". When you put your data into vectors/matrices/arrays then your code will be simpler and much more efficient: indexing is the key!
All you need is this (untested, just to get you started):
X = [2;4;5;7];
Y = [2;4;5;7];
for k = 1:numel(X)-1
vectarrow([X(k),Y(k)], [X(k+1),Y(k+1)])
end
To change the order using subscript indexing, e.g.:
v = [1,4,2,3]; % the order
for k = 1:numel(X)-1
vectarrow([X(v(k)),Y(v(k))], [X(v(k+1)),Y(v(k+1))])
end
See also your earlier question:
and read this:
  댓글 수: 1
Ole
Ole 2017년 8월 1일
Thank you!

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Logical에 대해 자세히 알아보기

제품

Community Treasure Hunt

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

Start Hunting!

Translated by