Compare pairs in an array with every other pair
조회 수: 4 (최근 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
댓글 수: 0
채택된 답변
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
추가 답변 (1개)
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.
댓글 수: 0
참고 항목
카테고리
Help Center 및 File Exchange에서 Logical에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!