Change variables in for loop
1 visualizzazione (ultimi 30 giorni)
Mostra commenti meno recenti
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 Commento
Stephen23
il 2 Giu 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.
Risposta accettata
Joseph Cheng
il 2 Giu 2021
Modificato: Joseph Cheng
il 2 Giu 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
0 Commenti
Più risposte (0)
Vedere anche
Categorie
Scopri di più su Whos in Help Center e File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!