Compare pairs in an array with every other pair
Show older comments
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
More Answers (1)
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.
Categories
Find more on Matrix Indexing in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!