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 CenterFile Exchange에서 Statistics 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