value from string ?

5 Ansichten (letzte 30 Tage)
Ole
Ole am 1 Aug. 2017
Kommentiert: Ole am 1 Aug. 2017
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 Kommentare
Stephen23
Stephen23 am 1 Aug. 2017
Bearbeitet: Stephen23 am 1 Aug. 2017
@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 am 1 Aug. 2017
Bearbeitet: Ole am 1 Aug. 2017
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

Melden Sie sich an, um zu kommentieren.

Akzeptierte Antwort

Stephen23
Stephen23 am 1 Aug. 2017
Bearbeitet: Stephen23 am 1 Aug. 2017
@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:

Weitere Antworten (0)

Produkte

Community Treasure Hunt

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

Start Hunting!

Translated by