Rapid calculation of the number of points in a circular neighbourhood
Show older comments
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
Robert
on 12 Jul 2026
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)
toc
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
S
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
Robert
on 12 Jul 2026
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
S
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
S
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
Robert
on 12 Jul 2026
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])
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{:}]
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
Robert
on 12 Jul 2026
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)
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
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
Robert
on 12 Jul 2026
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
denz
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
denz.'
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)
% compare timings
timeit(@() method1(xn,yn,rad))
timeit(@() method2(xn,yn,rad))
timeit(@() method3(xn,yn,rad))
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.
Robert
on 12 Jul 2026
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
denz.'
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
S
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)
[timeit(@() method1(xn,yn,rad)), timeit(@() method3(xn,yn,rad)), timeit(@() method4(xn,yn,rad))]
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
Robert
on 13 Jul 2026
Torsten
on 13 Jul 2026
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).
Robert
on 13 Jul 2026
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
denz(1:10)
Robert
on 13 Jul 2026
Robert
on 14 Jul 2026
Torsten
on 14 Jul 2026
You are welcome. Good luck for your further studies.
Accepted Answer
More Answers (2)
Walter Roberson
on 12 Jul 2026
1 vote
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.
James Tursa
on 18 Jul 2026
Edited: James Tursa
on 18 Jul 2026
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
Find more on Fortran with MATLAB in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!