Change variables in for loop

4 views (last 30 days)
Nick Jander
Nick Jander on 2 Jun 2021
Commented: Stephen23 on 2 Jun 2021
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 Comment
Stephen23
Stephen23 on 2 Jun 2021
"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.

Sign in to comment.

Accepted Answer

Joseph Cheng
Joseph Cheng on 2 Jun 2021
Edited: Joseph Cheng on 2 Jun 2021
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

More Answers (0)

Categories

Find more on Loops and Conditional Statements in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!