PDA

View Full Version : Mathematica Distance Matrix


brydustin
Mar8-11, 12:35 PM
I wanted to make a matrix whose elements are the Eucledian distance between row vectors in another matrix, obviously this matrix will be symmetric because distance(x,y) = distance(y,x).
I have had no difficulty doing this in Matlab but I can't do it in Mathematica

Here is my attempt
A = {{1, 2, 3}, {3, 2, 1}, {1, 1, 1}};
B = IdentityMatrix[3]

For[i = 1, i < 4, i++,
For[j = i, j < 4, j++
B[[i, j]] = Norm[A[[j]] - A[[i]]]
]
]
B = B + Transpose[B] - DiagonalMatrix[Diagonal[B]]

(*Where the last "trick" is done just so the loop is cut in half*)
Anyway, the loop part isn't working.... any suggestions?

Bill Simpson
Mar8-11, 01:49 PM
Outer[yourfunction,yourmat,yourmat,1] will perform yourfunction on every pair of rows in yourmat.
Total[(#1-#2)^2]& will subtract two rows, square the result and then sum up all the squares.

In[17]:= X={{a,b,c},{d,e,f},{g,h,i}};
Outer[Total[(#1-#2)^2]&,X,X,1]

Out[18]={{0, (a-d)^2+(b-e)^2+(c-f)^2, (a-g)^2+(b-h)^2+(c-i)^2},
{(- a+d)^2+(-b+e)^2+(-c+f)^2, 0, (d-g)^2+(e-h)^2+(f-i)^2},
{(-a+g)^2+(-b+h)^2+(-c+i)^2, (-d+g)^2+(-e+h)^2+(-f+i)^2, 0}}

In[19]:=X={{1,2,3},{3,2,1},{1,1,1}};
Outer[Total[(#1-#2)^2]&,X,X,1]

Out[20]={{0,8,5},
{8,0,5},
{5,5,0}}

brydustin
Mar8-11, 01:55 PM
In[17]:= X={{a,b,c},{d,e,f},{g,h,i}};
Outer[Total[(#1-#2)^2]&,X,X,1]

Out[18]={{0, (a-d)^2+(b-e)^2+(c-f)^2, (a-g)^2+(b-h)^2+(c-i)^2},
{(- a+d)^2+(-b+e)^2+(-c+f)^2, 0, (d-g)^2+(e-h)^2+(f-i)^2},
{(-a+g)^2+(-b+h)^2+(-c+i)^2, (-d+g)^2+(-e+h)^2+(-f+i)^2, 0}}

In[19]:=X={{1,2,3},{3,2,1},{1,1,1}};
Outer[Total[(#1-#2)^2]&,X,X,1]

Out[20]={{0,8,5},
{8,0,5},
{5,5,0}}


That's funny, I got run time error when trying your code.... which version are you using? I'm on 7.0.
What's the basic idea??

Bill Simpson
Mar8-11, 02:00 PM
Refresh the page and read the couple of lines I edited in for explanation.

Then try killing the kernel and running it fresh to make sure you don't have some value assigned to something.

If that doesn't help then tell me exactly what the runtime error is.

brydustin
Mar8-11, 02:16 PM
Thanks! That did the trick!
Like I said in my intro, I'm learning mathematica, and to me its very strange compared to matlab. Don't be surprised if you see a few more posts on this website by me on this topic, I'm doing a project for work. Thanks again!