Code for Given three points (x1, y1), (x2, y2) and (x3, y3), write a program to check if all the three points fall on one straight line.

105 views (last 30 days)
Given three points (x1, y1), (x2, y2) and (x3, y3), write a program to check if all the three points fall on one straight line.

Accepted Answer

Venkat Siddarth Reddy
Venkat Siddarth Reddy on 18 Apr 2024
Hi Ravi,
To achieve this you can use the concept of slopes i.e. if the slope between (x1, y1) and (x2,y2), and between (x2,y2) and (x3,y3) are equal then points lie on a straight line.
Following is the implementation of above logic in MATLAB
function isCollinear = checkCollinearity(x1, y1, x2, y2, x3, y3)
% Calculate the "slope" conditions using cross multiplication in case
% to avoid division.
% (y2 - y1) * (x3 - x2) == (y3 - y2) * (x2 - x1)
% If the above condition is true, then the points are collinear.
isCollinear = (y2 - y1) * (x3 - x2) == (y3 - y2) * (x2 - x1);
end
Call the above functions with the co-ordinates as arguments
% Define the points
x1 = 1; y1 = 1;
x2 = 2; y2 = 2;
x3 = 3; y3 = 3;
% Check if the points are collinear
if checkCollinearity(x1, y1, x2, y2, x3, y3)
disp('The points fall on one straight line.');
else
disp('The points do not fall on one straight line.');
end
The points fall on one straight line.
Hope it helps!

More Answers (0)

Categories

Find more on MATLAB in Help Center and File Exchange

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!