function in_out = insideTri( pt, a, b ) 
% The insideTri(pt,a,b) function determines whether a point 
% is inside or outside of a triangle.
%
% pt - must be a vector with the x and y coordinates of a single point
% a - must be a row vector with the x-coordinates of three vertices of a triangle
% b - must be a row vector with the y-coordinates of three vertices of a triangle
%
% Usage: to see if point (1.5,0.75) is inside the triangle formed by
%        the points (0,0), (2,1), and (0.5,2), use the command:
%
%          >> insideTri( [1.5,.75], [0 2 0.5], [0 1 2] ) 
%
%        The result of 0.5 indicates that this point is on the triangle.
%
% The method used is to compute the barycentric coordinates 
% of the point relative to the three vertex points. The array 
% coord contains the barycentric coordinates. If all of the 
% barycentric coordinates are nonnegative, then the point is 
% said to be inside the triangle. 
% If in_out is 1, the point is inside, 
% if in_out is 0, the point is outside,and 
% if in_out is 0.5, the point is on the edge. 

x = pt(1) ;   % extract the x-coord of the point pt
y = pt(2) ;   % extract the y-coord of the point pt 

A = [ 1, 1, 1 ; a ; b ] ; % Set up the coefficient matrix for the system. 
b = [ 1 ; x ; y ] ;       % Set up the data vector
coord = A\b ;             % Solve the linear system. 

if all( coord > 0 )       % If all barycentric coordinates are 
    in_out = 1 ;          % positive, the point is inside. 
elseif any( coord < 0 )   % If any coordinate is negative, 
    in_out = 0 ;          % the point is outside. 
else                      % Otherwise, 
    in_out = 0.5 ;        % it is on the boundary. 
end