You can try the code below, where function names perp_dist and xparal denotes perpendicular to AB and parallel to x-axis distances
R version
perp_dist <- function(P,A,B) {
norm(pracma::cross(c(P-A,0),c(B-A,0)),"2")/norm(B-A,"2") # use cross product of vectors to calculate the distance
}
xparal_dist <- function(P,A,B) {
AB <- B-A
perp_dist(P,A,B)*ifelse(AB[2]==0,1,sqrt(1+(AB[1]/AB[2])**2))
}
Example
A <- c(1,3)
B <- c(5,10)
P <- c(7,7)
perp_dist(P,A,B)
xparal_dist(P,A,B)
which gives
> perp_dist(P,A,B)
[1] 0.6933752
> xparal_dist(P,A,B)
[1] 0.8333333
Matlab version
function d = perp_dist(P,A,B)
d = norm(cross([P-A,0],[B-A,0]))/norm(B-A); % use cross product of vectors to calculate the distance
end
function d = xparal_dist(P,A,B)
AB = B-A;
if AB(2)==0
f = 1;
else
f = sqrt(1+(AB(1)/AB(2))^2);
end
d = perp_dist(P,A,B)*f;
end
Example
A = [0,0];
B = [6,9];
P = [2.5,2.5];
perp_dist(P,A,B)
xparal_dist(P,A,B)
such that
>> perp_dist(P,A,B)
ans = 0.6934
>> xparal_dist(P,A,B)
ans = 0.8333
Update (R language):
If you have A, B and P in form of data.frame, e.g.,
set.seed(1)
A <- data.frame(X = rnorm(5),Y = rnorm(5))
B <- data.frame(X = rnorm(5),Y = rnorm(5))
P <- data.frame(X = rnorm(5),Y = rnorm(5))
then you can use Vectorize over your data frames, i.e.,
dperp <- Vectorize(perp_dist)(data.frame(t(P)),data.frame(t(A)),data.frame(t(B)))
dxparal <- Vectorize(xparal_dist)(data.frame(t(P)),data.frame(t(A)),data.frame(t(B)))
such that
> dperp
X1 X2 X3 X4 X5
0.1916007 0.3101444 2.2245761 1.2821965 0.2617655
> dxparal
X1 X2 X3 X4 X5
0.5619376 0.3351336 3.2146859 19.9448870 0.3494685
Update 2 (R version)
If you want to calculate distance parallel to y axis, you can use the following code (MATLAB version is similar)
yparal_dist <- function(P,A,B) {
AB <- B-A
perp_dist(P,A,B)*ifelse(AB[1]==0,1,sqrt(1+(AB[2]/AB[1])**2))
}