MATLAB Answers

value from string ?

24 ビュー (過去 30 日間)
Ole
Ole 2017 年 8 月 1 日
Commented: 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 件のコメント

KSSV
KSSV 2017 年 8 月 1 日
The function accepts numbers/ double as input..you are not using it properly..
Stephen Cobeldick
Stephen Cobeldick 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 日
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

サインイン to comment.

採用された回答

Stephen Cobeldick
Stephen Cobeldick 2017 年 8 月 1 日
編集済み: Stephen Cobeldick 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!

サインイン to comment.

More Answers (0)

サインイン してこの質問に回答します。


Translated by