Change variables in for loop

1 次查看(过去 30 天)
Hello,
so I want to change variables in a for loop to use them in inpolygon.
I have the variables x_e1, x_e2, x_e3, y_e1, y_e3, y_e3 (and x,y) in my workspace (all of them are k long).
Unfortunately, my code below doesn't work.
for k=1:length(x)
for e=1:1:3
[in(k,e),on(k,e)]=inpolygon(x,y,strcat('x_e',num2str(e)),strcat('y_e',num2str(e));
end
end
Any help or advice is appreciated!
  1 个评论
Stephen23
Stephen23 2021-6-2
"Any help or advice is appreciated!"
Join those arrays into one/two arrays (which might be container array, e.g. cell array) and then use indexing.

请先登录,再进行评论。

采纳的回答

Joseph Cheng
Joseph Cheng 2021-6-2
编辑:Joseph Cheng 2021-6-2
That is because you're evaluating a string in that inpoly and not the variable x_e#... ideally you wouldn't want to do the evaluation with these kind of variables. best practice is not to have these kinds of variables especially if they are all the same length. you could create a single x and y variable for example
x_eNUM = [x_e1;x_e2;x_e3];
y_eNUM = [y_e1;y_e2;y_e3];
inwhich you can then index without having to "change" variable names like:
for k=1:length(x)
for e=1:1:3
[in(k,e),on(k,e)]=inpolygon(x(k),y(k),x_eNUM(e,:),y_eNUM(e,:));
end
end
which then as you can see in the x_eNUM example you evaluate the previously x_eNUM by accessing the first row to represent x_e1. also added in what i think you were going for where you check each k index in the point (x,y). previously above you were checking all of x and y against the x_e# and y_e# for length(x) times over and over.
if you are set on using x_e1,2,3 variables you can look at the funciton eval() which will evaluate a string but take a look at what i think you're attempting with the inpolygon(x(k), and y(k)....) adjustment i made

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Whos 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by