Home > Mobile >  Looking for a "vectorized" version to store difference of vector elements in matrix
Looking for a "vectorized" version to store difference of vector elements in matrix

Time:10-21

I am doing the following operation

a <- c(3, 7, 1)

M <- matrix(data = NA,
             nrow = 3,
             ncol = 3)
M
# a_i - a_j 
for(i in seq_along(a)) {
  
  for (j in seq_along(a)) {
    
    M[i, j] <- a[i] - a[j]
    
  }
}

and wonder if there is a more elegant, i.e. R-like way of doing this. In analogy to tcrossprod().

CodePudding user response:

We can use outer in base R

outer(a, a, `-`)

Or with sapply

sapply(a, `-`, a)

CodePudding user response:

If you really want to play with tcrossprod(), below might be a trick

> tcrossprod(a^0, a) - a
     [,1] [,2] [,3]
[1,]    0    4   -2
[2,]   -4    0   -6
[3,]    2    6    0

but nothing can be more efficient or elegant than outer, I think.

  • Related