17 views (last 30 days)
yavuz kahraman on 1 Apr 2016
Commented: Sanaz Kb on 25 Feb 2018
Hi,
I have a 4x6 matrix(A).
A= [50 56 76 55 63 63;
51 60 77 55 63 62;
51 60 77 55 64 64;
51 59 75 55 62 63]
Matrix A was formed as:
A=[X1 Y1 X2 Y2 X3 Y3]
or A=[point1 point2 point3] % point1 is (X1,Y1), point2(X2,Y2),
first column is keeping the x-coordinate...etc.
I have 4 observations(rows) and each observation has 3 points(6 columns). I want to calculate the eucledian distance and create a new matrix which is holding the all possible distances for each observation.
for example; distances for observation 1:
distance1=sqrt((X1-X2)^2 + (Y1-Y2)^2), %distance between point1 and point2
distance2=sqrt((X1-X3)^2 + (Y1-Y3)^2), %distance between point1 and point3
distance3=sqrt((X2-X1)^2 + (Y2-Y1)^2), %distance between point2 and point1
distance4=sqrt((X2-X3)^2 + (Y2-Y3)^2), %distance between point2 and point3
distance5=sqrt((X3-X1)^2 + (Y3-Y1)^2), %distance between point3 and point1
distance6=sqrt((X3-X2)^2 + (Y3-Y2)^2), %distance between point3 and point2 and
also repetitive distance is not important
I want to use any loop to creat my distances matrix which is shown below
distancesMatrix=[distance1 distance2 distance3 distance4 distance5 distance6]; % 4x6 matrix

John BG on 2 Apr 2016
Edited: Stephen23 on 25 Feb 2018
Yavuz
In this question you have only 3 points, but you may need more.
The function combinator.m is really useful when the amount of points increases, copy of combinator.m following these lines.
You mention in your question that you need the combinations with repetition. With 3 points makes 6:
combinator(3,2,'p')
=
2 1
1 2
3 1
1 3
3 2
2 3
However, since you are calculating distances you don't really need to calculate 6 distances, but just 3, because distance 1-2 is same as 2-1 and so on, then you need:
combinator(3,2,'c')
=
1 2
1 3
2 3
amount_points=3
amount_dist=numel(combinator(amount_points,2,'c'))/2 % how many distances to calculate for each round
[szA1 szA2]=size(A)
amount_observations=szA1 % how many rounds
distance=zeros(amount_observations,amount_dist) % make room for result
pair=combinator(amount_dist,2,'c') % all point pairs
for k=1:amount_observations
for j=1:amount_dist
distance(k,j)=(A(k,pair(j,1)).^2+A(k,pair(j,2)).^2).^.5
end
end
John
yavuz kahraman on 8 Apr 2016
Hi John,
İt is really helpfull. Thanks a lot.
I solved my problem thanks to your help.

Sanaz Kb on 23 Feb 2018
Edited: Sanaz Kb on 23 Feb 2018
Hello,
I have the same question. but instead of relating one-by-one points,I should relate all points with one reference point. could you pleas help me?
Another question: i implement your function code in my Matlab but it doesn't work. (It get me an error message in this line- error('Only 2, 3 or 4 inputs are allowed. See help.')-
Thanks
Sanaz Kb on 25 Feb 2018