MATLAB: Hi, i need help in plotting a triangle

hit and miss monte carloinpolygon

i need to plot a triangle using inpolygon function with particles distributed randomly in the xy axis.using hit and miss monte carlo method i need to calculate the percentage of particles inside the triangle and find the area of the triangle using the same.pls help.i am less than a beginner in matlab.

Best Answer

clc; clear all
vert = [0 0 ; 1 0 ; 1 1 ; 0 0] ;
% draw triangle
plot(vert(:,1),vert(:,2))
hold on
%%loop for random numbers
N = 1000 ; % more N, close the Area
x0 = min(vert(:,1)) ; x1 = max(vert(:,1)) ;
y0 = min(vert(:,2)) ; y1 = max(vert(:,2)) ;
count = 0 ;
for i = 1:N
xr = (x1-x0)*rand(1) + x0;
yr = (y1-y0)*rand(1) + y0;
plot(xr,yr,'.r') ;
% check whether (xr,yr) is inside triangle
in = inpolygon(xr,yr,vert(:,1),vert(:,2)) ;
if in==1
count = count+1 ;
plot(xr,yr,'.g') ;
drawnow
end
end
Area = count/N ;
% Area using formula
Af = polyarea(vert(:,2),vert(:,2)) ;
diff = Af-Area