I am trying to calculate the distance between a 2D point (though represented in 3D) and all the other 2D points in a 3D matrix, in order to determine which point in the matrix is closest to the individual. I prefer to use loops as little as possible.
Here's some example code:
vector = ones(1, 1, 2);matrix1 = magic(3);matrix2 = magic(3);%matrix1 is the x coord, matrix 2 the y coord
matrix = cat(3, matrix1, matrix2); %What I want it to do:
dists = norm(matrix-vector) %Size of dists should be (3,3,1)
[i,j,k]=ind2sub(size(dists), find(dists==min(dists(:)))) %Should return coordinates of smallest Euc dist
I just found bsxfun which duplicates the vector to subtract from the matrix:
diff = bsxfun(@minus, matrix, vector);
But then I still don't know how to make the matrices do the proper Euclidean distances between their points.
This does it, but still seems rather circuitous:
calc1 = bsxfun(@minus, matrix, vector);calc2 = calc1.^2;calc3 = sum(calc2, 3);calc4 = calc3.^(1/2);[winI,winJ] = ind2sub(size(calc4), find(calc4==min(calc4(:))));
Best Answer