value from string ?
2 次查看(过去 30 天)
显示 更早的评论
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
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?
采纳的回答
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:
https://www.mathworks.com/matlabcentral/answers/143-how-do-i-make-a-series-of-variables-a1-a2-a3-a10
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:
更多回答(0 个)
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Matrix Indexing 的更多信息
产品
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!