Calculating Distance Matrix in Mathematica

  • Context: Mathematica 
  • Thread starter Thread starter brydustin
  • Start date Start date
  • Tags Tags
    Mathematica Matrix
Join the discussion
Registration is free. Ask a follow-up in this thread, or start your own.
4 replies · 3K views
brydustin
Messages
201
Reaction score
0
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[]]
]
]
B = B + Transpose - DiagonalMatrix[Diagonal]

(*Where the last "trick" is done just so the loop is cut in half*)
Anyway, the loop part isn't working... any suggestions?
 
Physics news on Phys.org
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}}
 
Last edited:
Bill Simpson said:
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??
 
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.
 
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!