Dear all,
I would like to compute the point of a regular grid that is nearest to a given sample. I need also to keep track of the indexes of the nearest point.
I have implemented the following code, which works fine for small grids:
N = 100;
pp1 = linspace(0, 1, N);
pp2 = linspace(0, 1, N);
[P1, P2] = ndgrid(pp1, pp2);
querypoints = rand(2,N);
neighbours = zeros(N, 2);
distances = zeros(N*N, 1);
indexes = zeros(N*N, 2);
for j=1:N
z = 1;
for k=1:N
for l=1:N
distances(z) = norm(querypoints(:,j)-[P1(k,l);P2(k,l)]);
indexes(z,:) = [k, l];
z = z + 1;
end
end
[~, idx] = min(distances);
neighbours(j,:) = indexes(idx,:);
end
Unfortunately, if the number N of points increases my code become very very slow due to the three for cycles. Any idea to make my code faster (for instance through code vectorization)?
Any help is really appreciated. Thank you in advance!
Mauro