Compare pairs in an array with every other pair

3 views (last 30 days)
I have an r * 2 array in which each element in each row is a pair (a coordinate of a city). I have an function that can calculate the distance between any two cities (pairs of numbers), but I want to iterate through the array so that every pair(row) is compared to every other row. I just cannot figure out the indexing needed to pass the pairs into my function. I have tried for i=1:r for n=i+1:r
D(i,n)= function(i,n) end end But that of course doesn't compare the last row with the first!. Please help. thank you

Accepted Answer

Thorsten
Thorsten on 11 Nov 2015
Edited: Thorsten on 11 Nov 2015
Your code is correct. This produces all pairs in variable "pairs". A distance function is usually symmetric, so the the distance between last row and first row d(1,r) should be the same as the distance between first row and last row d(r,1). So it is ok that test each pair only once:
r = 8; pairs = [];
for i=1:r,
for n = i+1:r,
pairs(end+1, :) = [i n],
end
end
You can also use nchoosek to generate the pairs and then loop over the number of pairs
pairs2 = nchoosek(1:r, 2)
If you want to test all combinations, you just have to change the second for loop to
for n = 1:r
  13 Comments
Kim
Kim on 12 Nov 2015
Thorsten, Thank you again. This works perfectly but I don't understand why. If you have any time would you be able to explain why? Thanks
Kim
Kim on 12 Nov 2015
Thorsten, Thank you again. This works perfectly but I don't understand why. If you have any time would you be able to explain why? Thanks

Sign in to comment.

More Answers (1)

Image Analyst
Image Analyst on 12 Nov 2015
If you have the Statistics toolbox, you can also use pdist() and squareform().
% Get the distance from every point to every other point.
pDistances = pdist([points1;points2])
% That's hard to interpret though, so
% let's reshape that into a nice table
sfd = squareform(pDistances)
% Extract a table where the row index is the index of point 1,
% and the column index is the index of point 2
distances = sfd(1:numPoints1, numPoints1+1:end)
A full demo is attached.

Community Treasure Hunt

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

Start Hunting!