0

I have two matrixes:

matrixes with points

I would like to count the distance between point X and point Y without using a loop and in the way that when the matrix is expanded by additional columns the expression/function works.

For validation one could use:

sqrt((m1[,1] - m2[,1])^2 + (m1[,2] - m2[,2])^2 + (m1[,3] - m2[,3])^2 + (m1[,4] - m2[,4])^2 + (m1[,5] - m2[,5])^2)

The expression above gives the correct result for the distance between X and Y however once the matrix is expanded by additional columns the expression has also to be expanded and that is an unacceptable solution...

Would you be so kind and tell how to achieve this? Any help would be more than welcome. I'm stuck with this one for a while...

wounky
  • 97
  • 1
  • 12
  • 2
    Do not post your data as an image, please learn how to give a [reproducible example](http://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example/5963610) – Jaap Apr 23 '17 at 16:01

1 Answers1

1

- between matrix is element-wise in R and the rowSums is useful for calculating the sum of along the row:

m1 <- matrix(
    c(4, 3, 1, 6,
      2, 4, 5, 7,
      9, 0, 1, 2,
      6, 7, 8, 9,
      1, 6, 4, 3),
    nrow = 4
)

m2 <- matrix(
    c(2, 6, 3, 2,
      9, 4, 1, 4,
      1, 3, 0, 1,
      4, 5, 0, 2,
      7, 2, 1, 3),
    nrow = 4
)


sqrt((m1[,1] - m2[,1])^2 + (m1[,2] - m2[,2])^2 + (m1[,3] - m2[,3])^2 + (m1[,4] - m2[,4])^2 + (m1[,5] - m2[,5])^2)
# [1] 12.529964  6.164414  9.695360  8.660254

sqrt(rowSums((m1 - m2) ^ 2))
# [1] 12.529964  6.164414  9.695360  8.660254
mt1022
  • 16,834
  • 5
  • 48
  • 71