How to compute distance efficiently with no loops

5 ビュー (過去 30 日間)
etudiant_is
etudiant_is 2016 年 3 月 18 日
コメント済み: Guillaume 2016 年 3 月 18 日
I have matrices for points (not the same number of rows for P1 and P2) like this
P1=[12 45
34 7 ]
and
P2= [1 42 25
2 37 57
3 55 16]
What I what is to get the Manhattan (cityblock) distance between points in P1 (X and Y coordinates are in column 1 and 2) and those in P2 (X and Y are in column 2 and 3, the first one are indices of the points.
What I have been doing so far and works but very slow is with a nested for loop. But recently I saw pdist2 and I think it can help me avoid the loop.
But in the example, I need to put the whole matrix something like this
pdist2(P1,P2, 'cityblock');
But in my case, I want to use the columns of my matrices col as follows
abs(xP1(col1) - xP2(col2)) + abs(yP1(col2) - yP2(col3))
How can I do it or is there any faster way to do it (because i saw someone stating that even pdist uses nested for) since my matrices are quite big?

採用された回答

Guillaume
Guillaume 2016 年 3 月 18 日
Most likely:
pdist2(P1, P2(:, [2 3]), 'cityblock')
  4 件のコメント
etudiant_is
etudiant_is 2016 年 3 月 18 日
編集済み: etudiant_is 2016 年 3 月 18 日
Thank you for your help. Just one last thing, do you know if with pdist it will be faster than with nested loops or will it take similar time?
Guillaume
Guillaume 2016 年 3 月 18 日
I have no idea if it'll be faster. In theory, it should be. Why don't you test it?

サインインしてコメントする。

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeStatistics and Machine Learning Toolbox についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by