MATLAB: Calculating the distance matrix from coordiante matrix

distance matrix

Hello,
How can I calculate the distance matrix? for example I have the coordinate matrix: A=[3 5 4 5; 1 2 6 3] and I want to find the distance between each pair of points.
Thanks in advance for any help!

Best Answer

If you have the Stats Toolbox, pdist, as already mentioned:
A=[3 5 4 5; 1 2 6 3]
squareform(pdist(A'))
ans =
0 2.2361 5.099 2.8284
2.2361 0 4.1231 1
5.099 4.1231 0 3.1623
2.8284 1 3.1623 0
If you don't have the Stats Toolbox, you can calculate the distance manually:
dx = bsxfun(@minus, A(1,:), A(1,:)');
dy = bsxfun(@minus, A(2,:), A(2,:)');
sqrt(dx.^2 + dy.^2)
ans =
0 2.2361 5.099 2.8284
2.2361 0 4.1231 1
5.099 4.1231 0 3.1623
2.8284 1 3.1623 0