how can I sweep a triangle area using two loops
2 visualizaciones (últimos 30 días)
Mostrar comentarios más antiguos
Hello,
I want to sweep all points inside a triangle by coordinates (0,0), (2*pi/(3*a),0) and (0,4*pi/(3*a)) and by deviding this into two triangles and calculating line equations i wrote this code
for j=1:101
x=2*(j-1)*pi/(100*sqrt(3)*a);
for l=1:101
y=-(l-1)*x/(100*sqrt(3))+2*pi*(l-1)/(3*a*100);
for k=1:101
x=2*(k-1)*pi/(100*sqrt(3)*a);
for m=1:101
y=-(m-1)*x/(100*sqrt(3))+2*pi*(m-1)/(100*3*a)+2*pi/(3*a);
But this code doesn't cover some y points inside the triangle. What can i do for solving this problem?
3 comentarios
Respuestas (1)
Scott MacKenzie
el 20 de Jun. de 2021
Editada: Scott MacKenzie
el 20 de Jun. de 2021
No need for loops. The tests are built in to the inpolygon function when you provide matrices as input. Assuming you want to find points inside the triangle, given a "sweep" grid of x-y test points (integers or reals), then I think this achieves what you are after:
% your triangle points
a = 0.1;
xt = [0, 2*pi / (sqrt(3)*a), 0, 0];
yt = [0, 2*pi/(3*a), 4*pi/(3*a), 0];
% plot triangle with margin around edges
margin = 5;
x1 = round(min(xt)- margin);
x2 = round(max(xt)+ margin);
y1 = round(min(yt)- margin);
y2 = round(max(yt)+ margin);
axis([x1 x2 y1 y2]);
hold on;
plot(xt,yt);
% make a grid of points to find points inside and outside triangle
delta = 1; % granularity of grid (adjust as desired)
[X,Y] = ndgrid(x1:delta:x2,y1:delta:y2);
% test the points (logical matrix 'in' identifies points in/out)
in = inpolygon(X,Y,xt,yt);
% output number of points inside triangle
sum(sum(in))
% plot the points inside (blue) and outside (light blue)
plot(X(in),Y(in),'.b') % points inside
plot(X(~in),Y(~in),'.', 'color', [.7 .7 1]) % points outside
4 comentarios
Scott MacKenzie
el 20 de Jun. de 2021
Editada: Scott MacKenzie
el 20 de Jun. de 2021
I'm not sure what you mean by "all points" or "all appropriate y coordinates". The number of points inside the triangle is infinite. I included a variable delta for setting up ndgrid. The lower the value of delta the greater the number of points inside the triangle. Some stats here are...
Delta Number of Points inside triangle
1 781
0.1 76186
0.01 7599720
Ver también
Categorías
Más información sobre Creating and Concatenating Matrices en Help Center y File Exchange.
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!