MATLAB: Is possible to make radius flexible within rangesearch function

knnsearchMATLABrangerangesearch

Hello everyone,
I meet an urgent situation, I have around 300000 points which has x and y coordinate and I want to find all neighbors near the specified a set of points which about 10000 points with flexible radius.
I tried to use 'rangesearch' function, but the radius in that function is fixed. Then I try to use for loop to get the result, but the execution time is too long because my data size.
My for loop is written as below
%radius is a vector which length is 10000; data is a 300000-by-2 matrix,track is a 10000-by-2 matrix.
for i=1:10002
a=rangesearch(data,track,radius(i));
idx(i)=a(i);
end
So each track match a radius, and those 300000 points cut by different circle which has corresponding radius and center(track).
Anybody can help me simplified the code?

Best Answer

Yuyi,
I had this same problem today while performing a range search. Through a little fiddling, I managed to find a solution. The trick is to turn everything into a cell and perform cellfun .
First we make an anonymous function that applies the range search
searcher = @(X, Y, Radius) rangesearch(X, Y, Radius);
Now let's convert all of your data to cells. The only caveat is that data, track, and radius must have the same height. So if you want to use a particular radius on multiple searches, you must repeat that element in the radius matrix. So given that data is size [n, 2], track is size [n, 2], and radius is size [n, 1]
DataCell = mat2cell(data, ones(length(data), 1), 2);
TrackCell = mat2cell(track, ones(length(track), 1), 2);
RadiusCell = num2cell(radius)
Now we can apply the cellfun to these cells with the ability for a flexible search radius.
Result = cellfun(searcher, DataCell, TrackCell, RadiusCell, 'Uni', 0);
where the 'Uni', 0 stands for 'UniformOutput', 'False' because the results may all be different lengths.
Hope this helps you and anyone else who finds it.