# How do I determine the distance between ALOT of points smoothly?

1 vue (au cours des 30 derniers jours)
Kenneth le 5 Mai 2014
So, I have an array consisting of about 82000 x and y coordinates. I want to find out how many "neighbours" each points has within a radius of some value. I wrote something that does this, however the code takes roughly two months to compile...
I've been doing it with two for-loops (not a good idea), one running alle the points one by one and another checking the distance from the one point to each of the 82000 others. This does not work in practice.
Any good suggestions?
##### 0 commentairesAfficher -2 commentaires plus anciensMasquer -2 commentaires plus anciens

Connectez-vous pour commenter.

### Réponse acceptée

Friedrich le 5 Mai 2014
Hi,
you can do it using one for loop, e.g.
n = 82000;
A = rand(n,2);
nb = zeros(n,1);
dist = 0.1^2;
tic
for i=1:n-1
tmp = sum(power(bsxfun(@minus,A,A(i,:)),2),2);
nb(i) = sum(tmp < dist)-1;
end
toc
This needs approx. 94 seconds on my machine.
One can also parallelize that code pretty good (requieres Parallel Computing Toolbox), e.g.
pool = parpool(4);
tic
spmd
for i=labindex:numlabs:n-1
tmp = sum(power(bsxfun(@minus,A,A(i,:)),2),2);
nb(i) = sum(tmp < dist)-1;
end
end
toc
delete(pool)
Which needs approx. 67 seconds on my machine (not taking the worker startup/shutdown time into account). When you need to deal with more points to check the speedup should be even better.
##### 0 commentairesAfficher -2 commentaires plus anciensMasquer -2 commentaires plus anciens

Connectez-vous pour commenter.

### Plus de réponses (2)

Matt J le 5 Mai 2014
Modifié(e) : Matt J le 5 Mai 2014
##### 0 commentairesAfficher -2 commentaires plus anciensMasquer -2 commentaires plus anciens

Connectez-vous pour commenter.

Image Analyst le 5 Mai 2014
Try eliminating the square root in the distance calculation and finding how how many points distance squareds are within the radius squared (calculated before the loop):
for k = 1 : length(x)
....
distance2 = deltax^2 + deltay^2;
count = count + 1
##### 0 commentairesAfficher -2 commentaires plus anciensMasquer -2 commentaires plus anciens

Connectez-vous pour commenter.

### Catégories

En savoir plus sur Loops and Conditional Statements 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