MATLAB: Counting spheres within a certain radius of a sphere in a dense packing

spherical binning

I have a large set of X,Y,Z coordinates which define the centre points of my spheres in a certain packing. I want to be able to count the number of spheres within a particular distance of each sphere, i.e. how many sphere's are within 1R or 2R of each sphere.
At the moment I'm just checking which other coordinates are nearby using an if loop to check if delta x, y and z are less than 1R. If all 3 deltas are within than value then I count the point.
However as I do this with a large data set I want to try and see if there is a better way of doing this.
Any Suggestions?
JP

Best Answer

I'm going to think out loud on this one:
if you make three lists of you coordinates, each sorted by a different primary and secondary dimension (x,y,z), (y z x), (z x y) and had another list of the corresponding rows in each dimension. You could begin traversing at the row closest to the coordinate center you want, and work out in each dimension. Once a dimension has failed (e.g. y is too big, you quit traversing there, until all dimensions fail.
Edit Never mind, don't bother doing that. /edit
How many points do you have? I'd imagine a well vectorized brute-force approach could be pretty quick.
Point_we_care_about = [42 71 -30];
Max_radius = 200;
xyz_data = (rand(1000,3)-0.5)*1000;
rows_inside = sqrt(sum(bsxfun(@minus,Point_we_care_about,xyz_data).^2,2))<Max_radius;
%rows_inside is a logical vector of rows inside
find(rows_inside) %row Indices
Making xyz_data have 10000 rows it takes .0014 seconds on my system; 1/100 of a second with 100000 rows.