Rapid calculation of the number of points in a circular neighbourhood

I am trying to calcuate the number of neighbours a point has within a circular neighbourhood of radius, RAD, for a large number of points, n. (I am aiming for 10^6). The code I am using (given below) is practically instant for n=10^4, in the region of 1-2 mins for n=10^5 and circa 2 hrs for n=10^6. Unfortunatley this is impracticably slow for my purposes. I was unable to figure out a method of vectorising the calculation. Use of PARFOR radically improved performance over FOR to acheive the times given above. I don't have the ability to use GPUarrays. I am now out of ideas for improving performance. Any ideas?
n = 10^4; %Number of points
rad = 0.1; %Neighbourhood radius
denz = zeros(1,n);
xn = randn(1,n)'; %x-co-ordinates of points
yn = randn(1,n)'; %y-co-ordinates of points
parfor w=1:n
xntest = xn - xn(w);
yntest = yn - yn(w);
newcoords = [xntest yntest];
distances = sqrt(sum(newcoords.^2,2));
denz(w) = numel(find(distances < rad));
end

24 Comments

"pdist" requires a toolbox I don't have, unfortunately. The only extra toolbox I have is the parallel processing toolbox.
But I guess the full matrix will become too large for your available memory. So maybe comparing the first 1e3 points with all 1e5 points, then the next 1e3 points with all 1e5 points etc. and using pdist_oneline from above for the 100 steps necessary is an option.
Here is a comparison for N = 1e4. Surprisingly (at least for me), the splitting version is faster.
rng('default')
N = 1e4;
rad = 1;
x = randn(N,2);
tic
D = pdist_oneLine(x);
S = sum(D<rad,2)
S = 10000×1
805 1010 415 301 3840 1911 3548 3788 10 27 1833 85 3159 1522 3246
<mw-icon class=""></mw-icon>
<mw-icon class=""></mw-icon>
toc
Elapsed time is 0.606529 seconds.
tic
S = zeros(N,1);
for i = 1:100
y = x((i-1)*1e2+1:i*1e2,:);
D = pdist_oneLine(x,y);
S = S + sum(D<rad,2);
end
toc
Elapsed time is 0.179090 seconds.
S
S = 10000×1
805 1010 415 301 3840 1911 3548 3788 10 27 1833 85 3159 1522 3246
<mw-icon class=""></mw-icon>
<mw-icon class=""></mw-icon>
function [D] = pdist_oneLine(varargin)
% This is my one-line implementation that is equivalent to BOTH pdist and
% pdist2 which compute the Euclidean distance between all pairs of input
% observations. This implementation is completely vectorized, so it is much
% faster than any loop-based method, though it's not quite as fast as
% MATLAB's built-in pdist/pdist2 functions as those are executed from
% precompiled MEX files. Though computationally lite, the vectorization of
% this implementation makes it memory-intensive, so you run the risk of
% running out of RAM if the number of observations is sufficiently large.
% The built-in functions have protections against that but this
% implementation does not, so be warned!
%
%
% pdist USE:
%
% D = pdist_oneLine(X)
%
% For pdist use, simply input the set of observations X as a single n by k
% matrix, where n is the number of observations and k is the dimensionality
% of the observations' features (E.G. x-coordinates in the 1st column,
% y-coordinates in the 2nd column, etc). The output D will be an n by n
% matrix of the distances between each pair of observations from the input
% matrix X. Each measurement is repeated twice, making D symetric about its
% diagnonal. The diagonal represents distances between an observation and
% itself, so the diagonal is all zeros. For example, the distance between
% observations 5 and 7 (defined by rows 5 and 7 from the input matrix X,
% X(5,:) and X(7,:)) can be found at D(5,7) and D(7,5).
%
%
% pdist2 USE:
%
% D = pdist_oneLine(X,Y)
%
% For pdist2 use, simply input both sets of observations as separate
% matrices, X and Y, in the same format as the pdist use-case. The output D
% will be and n by m matrix of the distances between each pair of X and Y
% observations, where n and m are the number of X and Y observations,
% respectively. Each measurement in D is unqiue because X and Y contain
% unique observations. For example, the distance between observation 5 from
% X, X(5,:), and observation 7 from Y, Y(7,:), can be found at D(5,7).
%
%
% Author: Andrew M. Soltisz
% Email: andysoltisz@gmail.com
% GitHub: https://github.com/andrewsoltisz/pdist-one-line/tree/main
% MathWorks: https://www.mathworks.com/matlabcentral/fileexchange/136559-pdist_oneline
% Last Updated: 10/12/2023
%
% Copyright 2023, Andrew Michael Soltisz. All rights reserved.
% This source code is licensed under the BSD-3-Clause License found in the
% LICENSE.txt file in the root directory of this source tree.
D = squeeze(sqrt(sum(reshape(repmat(varargin{1},[1,size(varargin{end},1)])-reshape(varargin{end}',[1,numel(varargin{end})]),[size(varargin{1},1),size(varargin{1},2),size(varargin{end},1)]).^2,2)));
end
OK, so I got pdist_oneline working and I can do an absolute maximum of 4*10^4 points because of the array size/RAM limitations. I don't see how to break it into subsets, though, because if I did, I would get the distances between the points in contained in array A and the distances between the points contained in array B but none of the distances between points in A and points in B.
pdist_oneLine(x,y) computes the distances between x and y. So if {y(i),i=1,...,M} is a partition of x, you subsequently compute all the distances between x and x. See the example for N = 1e4 above - the results with and without splitting are identical.
Here is an example for N = 1e5. pdist2 instead of pdist_oneLine is faster by a factor of 3-4 - maybe you find an even more efficient version than pdist_oneLine on the File Exchange. Looking at the version with pdist_oneLine, there doesn't seem to be much performance gain compared with your code from above.
rng('default')
N = 1e5;
rad = 1;
x = randn(N,2);
tic
S = zeros(N,1);
parfor i = 1:100
y = x((i-1)*1e3+1:i*1e3,:);
D = pdist_oneLine(x,y);
S = S + sum(D<rad,2);
end
toc
Elapsed time is 51.620056 seconds.
S
S = 100000×1
26323 5486 5223 20444 14981 20160 31482 36801 178 1774 16450 513 30864 23727 25395
<mw-icon class=""></mw-icon>
<mw-icon class=""></mw-icon>
tic
S = zeros(N,1);
parfor i = 1:100
y = x((i-1)*1e3+1:i*1e3,:);
D = pdist2(x,y);
S = S + sum(D<rad,2);
end
toc
Elapsed time is 14.328267 seconds.
S
S = 100000×1
26323 5486 5223 20444 14981 20160 31482 36801 178 1774 16450 513 30864 23727 25395
<mw-icon class=""></mw-icon>
<mw-icon class=""></mw-icon>
function [D] = pdist_oneLine(varargin)
D = squeeze(sqrt(sum(reshape(repmat(varargin{1},[1,size(varargin{end},1)])-reshape(varargin{end}',[1,numel(varargin{end})]),[size(varargin{1},1),size(varargin{1},2),size(varargin{end},1)]).^2,2)));
end
I don't think pdist_oneLine computes the distance between x and y. See this example:
x=[0 1 2]'
y =[0 1 2]'
D = pdist_oneLine([x y])
It computes the distances between x(1),y(1) and x(1:n),(y(1:n), then x(2),y(2) and x(1:n),(y(1:n) and so on up to x(n),y(n). (n = 3 in this example.) You can easily see that the answers must be 0, sqrt(2) and 2*sqrt(2). The distances between x and y are all zero.
It looks like pdist_oneline computes exactly the same distances as in your original code.
x=[0 1 2]';
y =[0 1 2]';
D = pdist_oneLine([x y])
D = 3×3
0 1.4142 2.8284 1.4142 0 1.4142 2.8284 1.4142 0
<mw-icon class=""></mw-icon>
<mw-icon class=""></mw-icon>
xn = x;
yn = y;
n = 3;
for w=1:n
xntest = xn - xn(w);
yntest = yn - yn(w);
newcoords = [xntest yntest];
distances{w} = sqrt(sum(newcoords.^2,2));
end
[distances{:}]
ans = 3×3
0 1.4142 2.8284 1.4142 0 1.4142 2.8284 1.4142 0
<mw-icon class=""></mw-icon>
<mw-icon class=""></mw-icon>
Maybe pdist_oneline can be made less memory intensive by using singleton expansion rather than repmat?
function [D] = pdist_oneLine(varargin)
D = squeeze(sqrt(sum(reshape(repmat(varargin{1},[1,size(varargin{end},1)])-reshape(varargin{end}',[1,numel(varargin{end})]),[size(varargin{1},1),size(varargin{1},2),size(varargin{end},1)]).^2,2)));
end
I am now way out of my depth. I searched singleton expansion and the results were incomprehensible.
In my code, x and y are not the 2d components of the points you consider, but the full matrix of points with column 1 being the coordinates in the first and column 2 the coordinates in the second spatial dimension. Thus the following example computes the distances between points (1,2) and (2,-4) = D(1,1), (1,2) and (6,-1) = D(1,2), (3,4) and (2,-4) = D(2,1), (3,4) and (6,-1) = D(2,2), (5,6) and (2,-4) = D(3,1) and (5,6) and (6,-1) = D(3,2).
x = [1 2;
3 4;
5 6];
y = [2 -4;
6 -1];
D = pdist_oneLine(x,y)
D = 3×2
6.0828 5.8310 8.0623 5.8310 10.4403 7.0711
<mw-icon class=""></mw-icon>
<mw-icon class=""></mw-icon>
DD = zeros(size(x,1),size(y,1));
for i = 1:size(x,1)
for j = 1:size(y,1)
DD(i,j) = sqrt((x(i,1)-y(j,1))^2+(x(i,2)-y(j,2))^2);
end
end
DD
DD = 3×2
6.0828 5.8310 8.0623 5.8310 10.4403 7.0711
<mw-icon class=""></mw-icon>
<mw-icon class=""></mw-icon>
function [D] = pdist_oneLine(varargin)
D = squeeze(sqrt(sum(reshape(repmat(varargin{1},[1,size(varargin{end},1)])-reshape(varargin{end}',[1,numel(varargin{end})]),[size(varargin{1},1),size(varargin{1},2),size(varargin{end},1)]).^2,2)));
end
Unfortunately, your comment is incomprehensible to me. I think "not the 2d components of the points" means "not the x and y co-ordinates of the points." As to what the full matrix of points is, I don't know, whether you put it in bold type, or not. "Column 1 being the coordinates in the first and column 2 the coordinates in the second spatial dimension," means what? Columns of what? "Coordinates in the first spatial dimension" means what? The x-co-ordinates? Then you don't explain your notation so I have no idea what point(1,2) means, rendering everything after that meaningless to me.
This is your code together with the equivalent code using pdist2:
n = 10^4; %Number of points
rad = 0.1; %Neighbourhood radius
denz = zeros(1,n);
xn = randn(1,n)'; %x-co-ordinates of points
yn = randn(1,n)'; %y-co-ordinates of points
tic
for w=1:n
xntest = xn - xn(w);
yntest = yn - yn(w);
newcoords = [xntest yntest];
distances = sqrt(sum(newcoords.^2,2));
denz(w) = numel(find(distances < rad));
end
toc
Elapsed time is 0.755832 seconds.
denz
denz = 1×10000
38 37 1 7 36 19 8 48 44 33 28 3 19 26 36 28 23 7 23 5 15 14 40 39 12 35 23 19 32 53
<mw-icon class=""></mw-icon>
<mw-icon class=""></mw-icon>
x = [xn,yn];
denz = zeros(n,1);
tic
for w = 1:n
y = x(w,:);
D = pdist_oneLine(x,y);
denz = denz + sum(D<rad,2);
end
toc
Elapsed time is 0.862435 seconds.
denz.'
ans = 1×10000
38 37 1 7 36 19 8 48 44 33 28 3 19 26 36 28 23 7 23 5 15 14 40 39 12 35 23 19 32 53
<mw-icon class=""></mw-icon>
<mw-icon class=""></mw-icon>
function [D] = pdist_oneLine(varargin)
D = squeeze(sqrt(sum(reshape(repmat(varargin{1},[1,size(varargin{end},1)])-reshape(varargin{end}',[1,numel(varargin{end})]),[size(varargin{1},1),size(varargin{1},2),size(varargin{end},1)]).^2,2)));
end
rng(100)
n = 10^4; %Number of points
rad = 0.1; %Neighbourhood radius
xn = randn(1,n)'; %x-co-ordinates of points
yn = randn(1,n)'; %y-co-ordinates of points
% Method from original question
denz1 = method1(xn,yn,rad);
% Use pdist_oneline
denz2 = method2(xn,yn,rad);
% Use different version of pdist_oneline that avoids temporary memory use
% via repmat
denz3 = method3(xn,yn,rad);
% show all three methods equal
isequal(denz1,denz2,denz3)
ans = logical
1
% compare timings
timeit(@() method1(xn,yn,rad))
ans = 0.7116
timeit(@() method2(xn,yn,rad))
ans = 0.6957
timeit(@() method3(xn,yn,rad))
ans = 0.4930
Note that all three cases are calculating more than needed due to the symmetry in the problem, i.e., the distance from point-1 to point-2 is the same as the distance from point-2 to point-1. So I suspect some additional efficiency can be gained. For example, with n = 3 all three functions are computing 9 distances, even though only 3 actually need to be computed (3 are identically zero and the final 3 are the same as the first 3).
function denz = method1(xn,yn,rad)
n = numel(xn);
denz = zeros(1,n);
for w=1:n
xntest = xn - xn(w);
yntest = yn - yn(w);
newcoords = [xntest yntest];
distances = sqrt(sum(newcoords.^2,2));
denz(w) = numel(find(distances < rad));
end
end
function denz = method2(xn,yn,rad)
x = [xn,yn];
n = numel(xn);
denz = zeros(n,1);
for w = 1:n
y = x(w,:);
D = pdist_oneLine(x,y);
denz = denz + sum(D<rad,2);
end
denz = denz.';
end
function denz = method3(xn,yn,rad)
denz = sum(pdisttemp([xn,yn]) < rad,1);
end
function [D] = pdist_oneLine(varargin)
D = squeeze(sqrt(sum(reshape(repmat(varargin{1},[1,size(varargin{end},1)])-reshape(varargin{end}',[1,numel(varargin{end})]),[size(varargin{1},1),size(varargin{1},2),size(varargin{end},1)]).^2,2)));
end
function D = pdisttemp(W)
D = squeeze(vecnorm(reshape(W',1,2,[]) - W,2,2));
end
Unfortunately, method 3 for n = 1e6 is not realistic from the workspace needed. That's why I suggested to split the full x-array into portions y of some size, apply pdist2(x,y) and sum the results. But I don't know if this will be more efficient than the OP's original code. The results for N = 1e5 don't look like a big breakthrough.
x = [xn,yn];
denz = zeros(n,1);
tic
for w = 1:n
y = x(w,:);
D = pdist_oneLine(x,y);
denz = denz + sum(D<rad,2);
end
toc
When run with n=10^5, this took approx. 2.7x longer than my parfor loop.
As I wrote: no big breakthrough, almost the same execution times for both versions.
As the complete distance matrix is symmetric, you might gain some speed by only computing the distance d(a,b) once and not twice as d(a,b) and d(b,a) as @Paul mentionned.
n = 10^5; %Number of points
rad = 0.1; %Neighbourhood radius
denz = zeros(1,n);
xn = randn(1,n)'; %x-co-ordinates of points
yn = randn(1,n)'; %y-co-ordinates of points
tic
parfor w=1:n
xntest = xn - xn(w);
yntest = yn - yn(w);
newcoords = [xntest yntest];
distances = sqrt(sum(newcoords.^2,2));
denz(w) = numel(find(distances < rad));
end
toc
Elapsed time is 50.531972 seconds.
denz.'
ans = 100000×1
105 509 244 106 325 66 418 356 199 86 64 41 340 241 233
<mw-icon class=""></mw-icon>
<mw-icon class=""></mw-icon>
S = zeros(n,1);
x = [xn,yn];
tic
parfor i = 1:100
y = x((i-1)*1e3+1:i*1e3,:);
D = pdist_oneLine(x,y);
S = S + sum(D<rad,2);
end
toc
Elapsed time is 52.356474 seconds.
S
S = 100000×1
105 509 244 106 325 66 418 356 199 86 64 41 340 241 233
<mw-icon class=""></mw-icon>
<mw-icon class=""></mw-icon>
function [D] = pdist_oneLine(varargin)
D = squeeze(sqrt(sum(reshape(repmat(varargin{1},[1,size(varargin{end},1)])-reshape(varargin{end}',[1,numel(varargin{end})]),[size(varargin{1},1),size(varargin{1},2),size(varargin{end},1)]).^2,2)));
end
Method3 was really intended to show OP how to implement pdist_oneline using singleton expansion instead of repmat.
method4 modifies method1 to only compute the distances once. But I don't think method4 is parfor-able, though I'm not really a parfor user so coulde be wrong about that.
Also, it turns out vecnorm was a major bottleneck, so I got rid of that and the sqrt.
n = 10^4; %Number of points
rad = 0.1; %Neighbourhood radius
rng(100);
xn = randn(1,n)'; %x-co-ordinates of points
yn = randn(1,n)'; %y-co-ordinates of points
denz1 = method1(xn,yn,rad);
denz3 = method3(xn,yn,rad);
denz4 = method4(xn,yn,rad);
isequal(denz1,denz3,denz4)
ans = logical
1
[timeit(@() method1(xn,yn,rad)), timeit(@() method3(xn,yn,rad)), timeit(@() method4(xn,yn,rad))]
ans = 1×3
0.5865 0.4151 0.4103
<mw-icon class=""></mw-icon>
<mw-icon class=""></mw-icon>
function denz = method1(xn,yn,rad)
n = numel(xn);
denz = zeros(1,n);
rad2 = rad^2;
for w=1:n
xntest = xn - xn(w);
yntest = yn - yn(w);
newcoords = [xntest yntest];
distances = (sum(newcoords.^2,2));
denz(w) = numel(find(distances < rad2));
end
end
function denz = method4(x,y,rad)
W = [x,y];
n = size(W,1);
rad2 = rad^2;
denz = zeros(1,n);
for ii = 1:n
% d = (vecnorm(W(ii:end,:)-W(ii,:),2,2) < rad).';
d = ((sum((W(ii:end,:)-W(ii,:)).^2,2)) < rad2).';
denz(ii) = denz(ii) + sum(d,2);
denz(ii+1:end) = denz(ii+1:end) + d(2:end);
end
end
function denz = method3(xn,yn,rad)
denz = sum(pdisttemp2([xn,yn]) < rad^2,1);
end
function D2 = pdisttemp2(W)
D2 = squeeze(sum((reshape(W.',1,2,[]) - W).^2,2));
end
For fun, I coded the problem in FORTRAN and it took about 167 sec to run for n = 1e6 (with optimization level -O3).
Let me know if you are interested in the code.
I don't have a fortran compiler, so no, thanks.
This is my fasted Matlab version to date:
distances = sqrt(sum(coords.^2,2));
lowR = distances-rad;
highR = distances+rad;
inc = zeros(1,n);
parfor w=1:n
inc(w) = numel(distances(distances > lowR(w) & distances < highR(w)));
end
DISTANCES is a broadcast variable in the PARFOR loop and I don't know if I can get around that, but it's still way faster than the equivalent FOR loop.
The GNU Fortran compiler is for free.
MATLAB has many advantages (e.g. comfort of programming). But if speed matters, it is usually the wrong choice (at least from my experience).
I just got a result for 10^6 points of circa 46 mins, which is a huge improvement on where I started, though a snail's pace compared to your Fortran result. The investment of time involved in learning Fortran is, for me, unwarranted.
In principle, this is the FORTRAN code translated to MATLAB. Unoptimized, it takes about 17 sec, optimized 1.75 sec (using FORTRAN). So unoptimized, computation times are comparable.
n = 10^5; %Number of points
rad = 0.1; %Neighbourhood radius
rad2 = rad^2;
denz = zeros(1,n);
x = randn(1,n)'; %x-co-ordinates of points
y = randn(1,n)'; %y-co-ordinates of points
tic
for i = 1:n
counter = 0;
xi = x(i);
yi = y(i);
for j = 1:n
xn = x(j) - xi;
yn = y(j) - yi;
distance2 = xn^2 + yn^2;
if distance2 < rad2
counter = counter + 1;
end
end
denz(i) = counter;
end
toc
Elapsed time is 19.251045 seconds.
denz(1:10)
ans = 1×10
109 366 357 174 338 499 376 185 438 152
<mw-icon class=""></mw-icon>
<mw-icon class=""></mw-icon>
I'll investigate this when opportunity arises but that could be as late as next week, depending on how things play out.
With compiler options
gfortran -O3 -ftree-parallelize-loops=16
the code finishes within 25 sec for n = 1e6.
Amazing.
I tried your latest code; it takes circa 30 mins on my machine vs circa 45 mins for my parfor loop. When I first asked the question I was at circa 2 hrs, so that's a 4x speed increase which is pretty good. This is no longer the slowest part of my project and it looks unlikely that further radical improvement is possible without an unwarranted level of effort, so I'm going to accept this answer and thank one and all for their time and effort on my behalf.
You are welcome. Good luck for your further studies.

Sign in to comment.

 Accepted Answer

Did you try "pdist" ?
But maybe the distance matrix D will become too large in your case ... Then you might want to try the option
D = pdist(X,Distance,CacheSize=cache) or D = pdist(X,Distance,DistParameter,CacheSize=cache) uses a cache of size cache megabytes to accelerate the computation of Euclidean distances. This argument applies only when Distance is "fasteuclidean", "fastsquaredeuclidean", or "fastseuclidean".
rng('default')
N = 1e4;
rad = 1;
x = randn(N,2);
D = squareform(pdist(x));
S = sum(D<rad,2)
S = 10000×1
805 1010 415 301 3840 1911 3548 3788 10 27 1833 85 3159 1522 3246
<mw-icon class=""></mw-icon>
<mw-icon class=""></mw-icon>
Another option is "rangesearch":
idx = rangesearch(x,x,rad)
idx = 10000×1 cell array
{[1 2626 9002 8373 6811 1157 9326 7632 7259 6600 3446 7683 4349 2424 5060 7676 8677 1367 9269 5295 340 8664 9494 6965 7328 4347 3232 7808 2193 7900 5354 8125 … ] (1×805 double)} {[ 2 7558 9527 3187 1261 3762 8996 1632 2082 5492 3238 654 1967 9209 462 4411 495 3417 2066 8101 1454 740 6915 5889 6668 6061 3975 3534 8593 6733 2597 429 … ] (1×1010 double)} {[ 3 1189 577 7141 8580 2911 7477 1601 1414 3252 5995 1484 9359 2016 6373 8009 8674 4383 2532 1558 7745 172 6164 2635 5150 9596 1151 9831 5703 149 3558 638 … ] (1×415 double)} {[ 4 1861 2427 473 469 7602 8020 9587 8446 9108 6221 1561 4024 2362 1359 6524 8161 441 7483 2556 6824 7861 6525 6561 8491 564 9178 4904 1846 8233 7893 3322 … ] (1×301 double)} {[ 5 2225 3099 1184 2343 6864 9486 3351 2735 7649 7715 4675 3621 174 2432 5403 6657 3471 1268 6451 6625 976 5677 4958 6636 7716 2712 2802 8570 4624 492 6081 … ] (1×3840 double)} {[ 6 5183 5402 5800 2672 11 679 633 3197 1088 5961 7459 8195 4903 3898 8284 9161 8703 6017 6281 9135 715 76 9877 6361 5659 1658 317 1784 77 534 5484 8813 … ] (1×1911 double)} {[ 7 6321 2714 6345 2582 3068 8953 9288 6989 9977 2612 4593 7957 5621 8687 7997 9114 551 7462 804 680 4401 5947 4329 893 2924 5557 8037 449 4074 4102 3455 … ] (1×3548 double)} {[ 8 6278 6531 3561 43 7787 9240 5034 4700 5175 6187 5317 4361 6552 7485 7373 504 1210 6193 9314 2971 8540 2888 7283 6117 2321 4257 204 1774 6728 1870 4757 … ] (1×3788 double)} {[ 9 979 2539 3013 786 8364 1537 5933 3710 1538]} {[ 10 1655 7146 8605 5493 4481 1165 4762 259 6968 9731 2678 7491 1988 8330 9850 5115 1179 8412 1787 2449 8065 8838 7966 7959 8596 5095]} {[ 11 7459 5183 633 6 9135 76 8703 9161 5659 5961 5800 77 5402 3197 2672 6017 679 4903 1088 1658 8195 715 3898 6523 9877 8284 317 8813 3751 6361 7651 6281 … ] (1×1833 double)} {[ 12 9231 2940 6588 8978 508 5933 1040 6440 1693 1538 2325 7699 879 5405 2569 8364 7822 8336 675 1537 9556 3013 121 1986 3465 9446 1027 5033 1867 4075 2185 … ] (1×85 double)} {[ 13 8836 3383 1848 9383 23 9614 7539 579 1911 4673 5413 2517 3965 1579 3284 955 7005 7531 2006 7585 344 7678 1997 799 416 4230 1294 4200 1126 6171 1001 … ] (1×3159 double)} {[ 14 3149 2481 1399 2150 8668 7475 3836 3367 1865 3955 8652 6819 2261 9307 9500 136 1785 8046 6224 603 6913 4833 7881 5362 3236 7772 8258 1162 7978 6806 … ] (1×1522 double)} {[ 15 6823 8408 8769 9174 7896 6986 1095 6255 1279 2836 9416 1603 6214 4219 1679 3368 6404 5360 3752 2674 9223 4944 8231 1540 8936 7928 8639 2210 21 9467 … ] (1×3246 double)} {[ 16 119 192 5598 9280 2771 9511 4004 2540 2271 4359 7488 2777 3984 8918 803 7451 867 738 5407 1143 9747 79 540 705 9225 4924 951 4948 5082 8163 8326 9086 … ] (1×3895 double)}
cellfun(@numel,idx)
ans = 10000×1
805 1010 415 301 3840 1911 3548 3788 10 27 1833 85 3159 1522 3246
<mw-icon class=""></mw-icon>
<mw-icon class=""></mw-icon>

More Answers (2)

If the set of points is constant, but the location to examine varies, then historically an efficient implementation has been to use a quadtree decomposition. quadtree decomposition is sort of the two-dimensional equivalent of binary search, allowing you to do far fewer comparisons to determine the points within a search range.
Here is a C-mex routine to do the job. The run itself using the free MinGW64 C Compiler without any special optimizations or multi-threading:
>> mex neighbors.c
Building with 'MinGW64 Compiler (C)'.
MEX completed successfully.
>> neighbors_test3
n = 1000
Elapsed time is 0.003497 seconds.
SAME
n = 10000
Elapsed time is 0.027124 seconds.
SAME
n = 100000
Elapsed time is 1.878210 seconds.
SAME
n = 1000000
Elapsed time is 295.225661 seconds.
TOO LARGE ... NOT COMPARED
The m-code for this run:
% neighbors_test3.m
N = [1e3,1e4,1e5,1e6];
for m=1:numel(N)
n = N(m);
fprintf("n = %d\n",n);
r = 0.1;
X = randn(1,n);
Y = randn(1,n);
tic
D = neighbors(X,Y,r);
toc
if( n <= 1e5 )
d = zeros(size(X));
r2 = r*r;
for k=1:n
x = [X(1:k-1) X(k+1:end)];
y = [Y(1:k-1) Y(k+1:end)];
dx = X(k) - x;
dy = Y(k) - y;
d(k) = sum(dx.*dx+dy.*dy <= r2);
end
if( isequal(D,d) )
disp('SAME')
else
disp('DIFFERENT!')
end
else
disp('TOO LARGE ... NOT COMPARED')
end
end
The C-mex source code for this run:
// neighbors.c
// Given a set of points defined by X and Y arrays, returns how many neighbors
// are within a distance r for each point
// C = neighbors(X,Y,r)
// X = real full double N-element array (x-positions)
// Y = real full double N-element array (y-positions)
// r = real numeric scalar
// C = real full double N-element array (counts number of neighbors)
// Programmer: James Tursa
// Date: July 18, 2026
//
//\
// MATLAB-mex Gateway
///
#include "mex.h"
void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[])
{
double r2, dx, dy;
double *X, *Y, *C, *x, *y, xp, yp;
mwSize i, j, n;
//\
// Argument checks
///
if( nrhs != 3 ) {
mexErrMsgTxt("Need exactly three inputs");
}
if( nlhs > 1 ) {
mexErrMsgTxt("Too many outputs");
}
if( !mxIsDouble(prhs[0]) || mxIsSparse(prhs[0]) || mxIsComplex(prhs[0]) ) {
mexErrMsgTxt("1st input must be real full double array");
}
if( !mxIsDouble(prhs[1]) || mxIsSparse(prhs[1]) || mxIsComplex(prhs[1]) ) {
mexErrMsgTxt("2nd input must be real full double array");
}
if( !mxIsNumeric(prhs[2]) || mxIsComplex(prhs[2]) || mxGetNumberOfElements(prhs[2]) != 1 ) {
mexErrMsgTxt("3rd input must be real numeric scalar");
}
if( mxGetNumberOfElements(prhs[0]) != mxGetNumberOfElements(prhs[1]) ) {
mexErrMsgTxt("1st and 2nd inputs must have same number of elements");
}
//\
// Get radius and pointers
///
X = (double *) mxGetData(prhs[0]);
Y = (double *) mxGetData(prhs[1]);
r2 = mxGetScalar(prhs[2]); r2 = r2 * r2;
n = mxGetNumberOfElements(prhs[0]);
//\
// Create output variable
///
plhs[0] = mxCreateDoubleMatrix(1,n,mxREAL);
C = (double *) mxGetData(plhs[0]);
//\
// Loop through all of the points
///
for( i=0; i<n; i++ ) {
xp = *X;
yp = *Y;
x = X++ + 1;
y = Y++ + 1;
for( j=i+1; j<n; j++ ) {
dx = *x++ - xp;
dy = *y++ - yp;
if( dx*dx + dy*dy <= r2 ) {
C[i]++; C[j]++;
}
}
}
}

Categories

Products

Release

R2024b

Asked:

on 12 Jul 2026

Edited:

on 18 Jul 2026

Community Treasure Hunt

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

Start Hunting!