MATLAB: Newbie: Euclidean distance of a matrix?

distance matrixeuclidean distance

hello all, i am new to use matlab so guys i need ur help in this regards. if i have a mxn matrix e.g
X=[5 3 1; 2 5 6; 1 3 2]
i would like to compute the distance matrix for this given matrix as
D= [d11 d12 d13; d21 d22 d23; d31 d32 d33]
where d(ij)= euclidean distance between row i and j.
in my thinking i applied a for loop like this
% for r=1:rows
% for c=1:cols
% for k=1:3
% d(r,c)= sqrt(sum(a(r,k)-a(c,k)).^2);
% end
% end
% end
but this thing doen't gives the desired result. can some one please correct me and also it would b nice if it would be not only for 3×3 matrix but for any mxn matrix..
thanks alot in advance i wish a nice smilling day

Best Answer

Following your rules:
X=[5 3 1; 2 5 6; 1 3 2]; %sample matrix
myEdist = squeeze(sqrt(sum(bsxfun(@minus,X,reshape(X',1,size(X,2),size(X,1))).^2,2))) %Engine
Take the difference of elements in each combination of rows. Square it, sum it, root it, and squeeze it!.