Is there a way to calculate the following specified matrix by avoiding loops? in R or Matlab
- 阅读更多 关于 Is there a way to calculate the following specified matrix by avoiding loops? in R or Matlab
问题 I have an N-by-M matrix X , and I need to calculate an N-by-N matrix Y : Y[i, j] = sum((X[i,] - X[j,]) ^ 2) 0 <= i,j <= N For now, I have to use nested loops to do it with O(n 2 ). I would like to know if there's a better way, like using matrix operations. more generally, sum(....) can be a function, fun(x1,x 2) of which x1 , x2 are M-by-1 vectors. 回答1: you can use expand.grid to get a data.frame of possible pairs: X <- matrix(sample(1:5, 50, replace=TRUE), nrow=10) row.ind <- expand.grid(1