# Compute the row-wise distance of two matrix

Suppose I have a matrix x of size `m x p`, and another matrix y of size `m x p`, how to compute the pdist2(in matlab) of
the two matrices, which gives me a matrix ``` m x m `` , each element d_ij = dist(x_i, y_j), where x_i and y_j is the coresponding row vecor. can any one give some elegant solution?

``````mp1 = torch.rand(m,p)
mp2 = torch.rand(m,p)
mmp1 = torch.stack([mp1]*m)
mmp2 = torch.stack([mp2]*m).transpose(0,1)
mm = torch.sum((mmp1-mmp2)**2,2).squeeze()
``````

Then mm is the m*m matrix you want, with mm_ij = d(mp1_i, mp2_j)

4 Likes

Very elegant solution. Thank you very much.

1 Like