Examples

  1. You have been given the insideTriangle() function that returns 1 if the point is inside the specified triangle.

    You do not need to understand how this function works. At least, not yet. But, you do need to know how to use the function and you need to test its accuracy before using it to solve any problems. Copy and save the insideTriangle.m function to your workspace.

    Enter the following in the command window to create the vertices, A, B, and C of a triangle.

                >> A=[0 0] 
                >> B=[2 0] 
                >> C=[1 1] 
                

    Enter the following to create a point to test.

    >> pt = [1 0.5]

    Enter the following to plot the triangle and the first point. Visually determine if the point is inside the specified triangle.

    >> plot( [ A(1) B(1) C(1) A(1)], [ A(2) B(2) C(2) A(2) ] , pt(1), pt(2), 'o' )
    Here is the plot of the specified triangle and the point.

    the point is inside the triangle

    As you can see the point is inside the triangle. Now, we're ready to test our insideTriangle function to see if it returns the correct result.

  2. Call the insideTriangle function as follows to see if the point is inside the triangle. The insideTriangle function returns 1 if the the point is inside the triangle, 0 if the point is outside the triangle, and 0.5 if the point is on the triangle.
    >> insideTriangle(A,B,C,pt)
    >> insideTriangle(A,B,C,pt)
    
    ans =
    
         1
    
    >> 

    Yay! Our function works for this pt and triangle combination. However, it is important to test other triangle and point combinations to ensure that it works for all triangles.

  3. Repeat the above steps to see if each of these points are inside the specified triangle.

    1) A=[0 0] B=[2 1] C=[1 3] and pt=[1 1]
    2) A=[0 0] B=[1 2] C=[2 0] and pt=[1 1]
    3) A=[-1 -1] B=[1 3] C=[2 0] and pt=[-1 1]

    >> insideTriangle([0 0],[2 1],[1 3],[1 1])
    
    ans =
    
         1
    
    >> insideTriangle([0 0],[1 2],[2 0],[1 1])
    
    ans =
    
         1
    
    >> insideTriangle([-1 -1],[1 3],[2 0],[0 1])
    
    ans =
    
         0.5000
         
    >> insideTriangle([-1 -1],[1 3],[2 0],[-1 1])
    
    ans =
    
         0
    
    >> plot([-1 1 2 -1],[-1 3 0 -1],-1,1,'o')
    >> 

    Here is the plot of the last example. You can see that the point (-1,1) is not inside the triangle.

    the point is not inside the triangle

    Try some other triangles and points to be sure.