How to compute distance efficiently with no loops

3 vues (au cours des 30 derniers jours)
etudiant_is
etudiant_is le 18 Mar 2016
Commenté : Guillaume le 18 Mar 2016
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?

Réponse acceptée

Guillaume
Guillaume le 18 Mar 2016
Most likely:
pdist2(P1, P2(:, [2 3]), 'cityblock')
  4 commentaires
etudiant_is
etudiant_is le 18 Mar 2016
Modifié(e) : etudiant_is le 18 Mar 2016
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 le 18 Mar 2016
I have no idea if it'll be faster. In theory, it should be. Why don't you test it?

Connectez-vous pour commenter.

Plus de réponses (0)

Catégories

En savoir plus sur Statistics and Machine Learning Toolbox dans Help Center et File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by