I am trying to optimize this piece of code and get rid of the nested loop implemented. I am finding difficulties in applying a matrix to pdist function
For example, 1+j // -1+j // -1+j // -1-j are the initial points and i am trying to detect 0.5+0.7j to with point it belong by min distance approach .
any help is appreciated
function result = minDisDetector( newPoints, InitialPoints)
result = [];
for i=1:length(newPoints)
minDistance = Inf;
for j=1:length(InitialPoints)
X = [real(newPoints(i)) imag(newPoints(i));real(InitialPoints(j)) imag(InitialPoints(j))];
d = pdist(X,'euclidean');
if d < minDistance
minDistance = d;
index = j;
end
end
result = [result; InitialPoints(index)];
end
end
You can use efficient euclidean distance calculation as listed in Speed-efficient classification in Matlab
for a vectorized solution
-
%// Setup the input vectors of real and imaginary into Mx2 & Nx2 arrays
A = [real(InitialPoints) imag(InitialPoints)];
Bt = [real(newPoints).' ; imag(newPoints).'];
%// Calculate squared euclidean distances. This is one of the vectorized
%// variations of performing efficient euclidean distance calculation using
%// matrix multiplication linked earlier in this post.
dists = [A.^2 ones(size(A)) -2*A ]*[ones(size(Bt)) ; Bt.^2 ; Bt];
%// Find min index for each Bt & extract corresponding elements from InitialPoints
[~,min_idx] = min(dists,[],1);
result_vectorized = InitialPoints(min_idx);
Quick runtime tests with newPoints
as 400 x 1
& InitialPoints
as 1000 x 1
:
-------------------- With Original Approach
Elapsed time is 1.299187 seconds.
-------------------- With Proposed Approach
Elapsed time is 0.000263 seconds.