Reputation: 8528
This should be an easy one. I am trying to find the coordinates of a point on a straight line. I am implementing in MATLAB. I know, the coordinates of the endpoints and the distance from one of the point.
I am using the following formula for calculating the coordinates (please note, I cannot use mid-point formula, as the distance can vary).
I am getting the wrong results when the slope is negative. Can you please suggest, what are the conditions, that needs to be considered for using this formula? Am not aware of any other formula as well.
Upvotes: 2
Views: 5448
Reputation: 38032
Nothing wrong with your solution, but you need to take care of quadrant ambiguities when you take the arctangent to compute the angle θ.
There is a nice solution for that in most programming languages: atan2
. Thus:
%// Your points (fill in any values)
A = [-10 0];
B = [-1 -1];
%// Use atan2!
th = atan2( B(2)-A(2) , B(1)-A(1) );
%// Distance from A to the point of interest
AP = sqrt( (B(2)-A(2))^2 + (B(1)-A(1))^2 ) / 2;
%// The point of interest
C = [
A(1) + AP*cos( th )
A(2) + AP*sin( th )];
%// Verify correctness with plots
figure(1), clf, hold on
line([A(1); B(1)], [A(2); B(2)])
plot(...
A(1), A(2), 'r.',...
B(1), B(2), 'b.',...
C(1), C(2), 'k.', 'markersize', 20)
In general, whenever and wherever you need to take an arctangent, use atan2
and not atan
. The normal atan
is only for cases where you don't know the individual components of the division y/x
.
Note that your solution is not extensible to 3D, whereas the vector solutions proposed by the others here are. So in general I would indeed advise you to start working with vectors. Not only is it a lot simpler in many circumstances, it is also more versatile.
Upvotes: 3
Reputation: 21749
That's too complicated solution for such a simple task. Use direct vector computations:
function P = point_on_line(A, B, AP)
D = B - A;
P = A + D / norm(D) * AP;
end
Call like this:
P = point_on_line([x1 y1], [x2 y2], len);
x = P(1);
y = P(2);
Ask if you need any clarifications.
Upvotes: 5
Reputation: 1965
This is a wrong approach to the solution, as the solution is not unique. There are two points on you line with the same distance AP from the point A: one going left and another one going right.
The are infinite approaches to solve this, I prefer vector notation.
vector ab is a 2x1 matlab matrix:
ab = B-A
abN is the normalized vector
abN = ab/norm(ab)
stepping from A in the abN direction a distance of d (in your case AP) is:
A + abN*d
hope it helped.
Ohad
Upvotes: 3