MATLAB Answers

Change variables in for loop

조회 수: 1(최근 30일)
Nick Jander
Nick Jander 2021년 6월 2일
댓글: Stephen 2021년 6월 2일
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
Stephen
Stephen 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개)

Community Treasure Hunt

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

Start Hunting!

Translated by