First let's take a quick look at what your code is doing. Your innermost line of code is:
n[i]<-sum(abs(a[i,]-b[j,])^2)
Due to how you've structured your for loops, this is run for times
- with i=1 and j=1, setting
n[1]
to the squared distance between row 1 with a
and row 1 of b
,
- with i=1 and j=2, overwriting
n[1]
to the squared distance between row 1 of a
and row 2 of b
,
- with i=2 and j=1, setting
n[2]
to the squared distance between row 2 of a
and row 1 of b
, and
- with i=2 and j=2, overwriting
n[2]
to the squared distance between row 2 of a
and row 2 of b
.
So we end up with n = c(34, 20)
, the squared distances between each row of a
and the last row of b
.
It seems most likely to me that you are trying to compute the distances between each pair of points (since your n
is structured as a vector). In this case, check out what we accomplish with the following, much simpler code:
(a-b)^2
# [,1] [,2]
# [1,] 4 16
# [2,] 4 16
The resulting matrix is the squared difference of each element in the two matrices. All we need to do is to sum up the rows:
n <- rowSums((a-b)^2)
n
# [1] 20 20
Or if we wanted the actual distance instead of the squared distance:
n <- sqrt(rowSums((a-b)^2))
n
# [1] 4.472136 4.472136
Note that we dramatically simplified the calculation; a nice side benefit is that this code is much faster than using a for
loop in R.
proxy
package, you can doproxy::dist(a, b, method = "Euclidean")
. \$\endgroup\$