Search code examples
rdot-productcombn

combn() function in r


I'm trying to perform the dot product on all possible combinations of vectors. I am able to find all the possible combinations. I just can't quite figure out how the FUN argument in combn() works. Below is my code, thanks for any help!

def=c("Normal.def","Fire.def","Water.def","Electric.def","Grass.def","Ice.def",
       "Fighting.def","Poison.def","Ground.def","Flying.def","Pyschic.def","Bug.def",
       "Rock.def","Ghost.def","Dragon.def","Null.def")

combn(def,2,FUN=def%*%def,simplify=TRUE)

Solution

  • Why don't you just matrix multiply the whole thing. For example:

    set.seed(1)
    vec1 <- sample(1:10)
    vec2 <- sample(1:10)
    vec3 <- sample(1:10)
    
    rbind(vec1, vec2, vec3) %*% cbind(vec1, vec2, vec3)
    

    produces:

         vec1 vec2 vec3
    vec1  385  298  284
    vec2  298  385  296
    vec3  284  296  385
    

    Where each cell of a matrix is the dot product of the two vectors in the col and row labels. Alternatively, if you really want to do it with combn:

    vec.lst <- list(vec1, vec2, vec3)
    combn(
      seq_along(vec.lst), 2, 
      FUN=function(idx) c(vec.lst[[idx[[1]]]] %*% vec.lst[[idx[[2]]]])
    )
    

    Which produces:

    [1] 298 284 296
    

    Notice how those numbers correspond to the upper triangle of the matrix. For small data sets the matrix multiply approach is much faster. For large ones, particularly ones were the vectors are very large but there aren't that many of them, the combn approach might be faster since it doesn't run as many computations (only the upper triangle basically).