The problem with your problem is to make an N * N matrix, and the result should return in that matrix without using loops. I overcome this problem by providing a suitable size for the Bsxfun function. By default, X and ReshapedX must be the same size when calling the bsxfun function. But if the size of the matrices is not equal, and one of them has a singleton (equal to 1) dimension, the matrix is actually replicated along this dimension in accordance with the other matrix. Therefore, it returns the matrix N * 3 * N, which provides the subtraction of each three-dimensional point from the others.
ReshapedX = permute(X,[3,2,1]); DiffX = bsxfun(@minus,X,ReshapedX); DistX =sqrt(sum(DiffX.^2,2)); D = squeeze(DistX);
source share