Compare pairs in an array with every other pair

3 次查看(过去 30 天)
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

采纳的回答

Thorsten
Thorsten 2015-11-11
编辑:Thorsten 2015-11-11
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 个评论
Kim
Kim 2015-11-12
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 2015-11-12
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

请先登录,再进行评论。

更多回答(1 个)

Image Analyst
Image Analyst 2015-11-12
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.

类别

Help CenterFile Exchange 中查找有关 Matrix Indexing 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by