Faster way to calculate pairwise distance?
Mostrar comentarios más antiguos
I have a matrix p x n, with row vector as coordinate in space. I need to calculate distance between all pairs of these coordinates. Since my p is very large(~50,000), I want to write the code without using any for loop and using only built-in function. I have reduced the code till 1 for loop, still it takes lot of time. I have only signal processing toolbox available with me.
My code looks like this:
if true
Y = a + rand(50000,5)*(b-a);
for i=1:p-1
j=i+1:p
D(j,i) = sqrt(sum(bsxfun(@minus,Y(i,:),Y(j,:)).^2,2));
end
end
Any help would be much appreciated.
1 comentario
Matt Kindig
el 1 de Mzo. de 2013
Well the first thing you could do is pre-allocate D, by inserting this line prior to the for loop:
D = zeros(p-1,p);
However, Shashank is right--you will run into major issues with memory soon.
Respuestas (1)
Shashank Prasanna
el 1 de Mzo. de 2013
pdist
But part of the statistics toolbox.
Alternatively you could generate all pairwise combinations of row using
nchoosek
And then calculate distance as above. But you may hit the memory wall, as the nchoosek output will be huge.
Categorías
Más información sobre Loops and Conditional Statements en Centro de ayuda y File Exchange.
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!