How to compute distance efficiently with no loops

3 次查看(过去 30 天)
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 CenterFile Exchange 中查找有关 Downloads 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by