Search code examples
matlabmathpositionline

Defining which side of a line point is. Special case


I have written a Matlab code, which allows to define which side of a line point is. It works fine for many cases, but I've found one special case when it works weird. Here is the code:

clear all
close all
clc
polylineX = [9 15];
polylineY = [7 6];
hold on
for i = 1:27
    for j = 1:32
        point(1) = j-10;
        point(2) = i-101;
        pos = sign((polylineX(2) - polylineX(1)) * (point(2) - polylineY(1)) -...
                   (polylineY(2) - polylineX(1)) * (point(1) - polylineX(1)));

        if pos == 1
            plot(point(1),point(2),'r.','MarkerSize',5)
        elseif pos == -1
            plot(point(1),point(2),'m.','MarkerSize',5)
        elseif pos == 0
            plot(point(1),point(2),'k.','MarkerSize',5)
        end;
        pause(0.00000001);
    end;
end;
plot(polylineX,polylineY)

Here is the result:

Result of the program

Red color is for 'left' position, 'magenta' color is for right position, 'black' color is for the position on the line. You can see the blue line as well relative position to which I am trying to estimate. As you can see the result is drawn as it was for another line.

What's wrong?

When implementing the code I looked, for example, here:

  1. Calculate on which side of a line a point is

  2. How to tell whether a point is to the right or left side of a line


Solution

  • You have a mistake in your formula:

    polylineY(2) - polylineX(1)
    

    should be

    polylineY(2) - polylineY(1)
    

    to calculate the correct determinant.