Filter löschen
Filter löschen

Compare pairs in an array with every other pair

3 Ansichten (letzte 30 Tage)
Kim
Kim am 11 Nov. 2015
Beantwortet: Image Analyst am 12 Nov. 2015
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

Akzeptierte Antwort

Thorsten
Thorsten am 11 Nov. 2015
Bearbeitet: Thorsten am 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 Kommentare
Kim
Kim am 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 am 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

Melden Sie sich an, um zu kommentieren.

Weitere Antworten (1)

Image Analyst
Image Analyst am 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.

Kategorien

Mehr zu Matrix Indexing finden Sie in Help Center und File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by