Reputation: 21
Description of the program is as below:
I take 3 coordinates from a file and I drew a triangle
I want to plot a grid and if the grid points are in a triangle, I want to plot a black circle, otherwise a red circle.
The method I used for checking if the point is inside a triangle is, if the point (xco,yco) is inside the triangle, the sum of areas of small triangles it makes with three other points is equal to the area of the triangle.
So my if statement is if the total area = area of triangle -> plot black circle, otherwise red circle.
The problem is, even though some points made the Total area to be equal to the area of the triangle plot black circle isn't plotted and red circle is plotted instead.
It does seem random and I can't figure out this simple problem.
So could you help me with the plotting the the points?
figure()
% Loading the data from .mat file
A = load('triangle_a.mat','pt1');
B = load('triangle_a.mat','pt2');
C = load('triangle_a.mat','pt3');
% Assigning values of array from .mat into each variable
x1 = A.pt1(1,1);
y1 = A.pt1(1,2);
x2 = B.pt2(1,1);
y2 = B.pt2(1,2);
x3 = C.pt3(1,1);
y3 = C.pt3(1,2);
% Drawing coordinates of a triangle on a grid
plot(x1, y1,'or');
hold on
plot(x2, y2,'or');
hold on
plot(x3, y3,'or');
hold on
% Joining three coordinates to make a triangle
plot ([x1,x2],[y1,y2],'-b');
plot ([x1,x3],[y1,y3],'-b');
plot ([x3,x2],[y3,y2],'-b');
xmin = A_coor(1,1);
xmax = B_coor(1,1);
ymin = A_coor(1,2);
ymax = C_coor(1,2);
xgrid = xmin-1:0.5:xmax+1;
ygrid = ymin-1:0.5:ymax+1;
tri_x = [x1 x2 x3];
tri_y = [y1 y2 y3];
area = polyarea(tri_x,tri_y);
% Making a grid
for x = 1:1:numel(xgrid)
for y = 1:1:numel(ygrid)
xco = xgrid(1,x);
yco = ygrid(1,y);
aa = [xco, x2, x3];
bb = [yco, y2, y3];
cc = [x1, xco, x3];
dd = [y1, yco, y3];
ee = [x1,x2,xco];
ff = [y1,y2,yco];
area1 = polyarea(aa,bb);
area2 = polyarea(cc,dd);
area3 = polyarea(ee,ff);
totarea = area1 + area2 + area3;
if totarea == area
plot(xco,yco,'ok');
else
plot(xco,yco,'.r');
end
end
end
My code worked after I changed the condition of if statement for making a grid section. (Thanks to Hoki for suggestion)
Before
if totarea == area
After
if abs(area-totarea)<0.002;)
Upvotes: 2
Views: 185