0

The solution provided here: Sparse Matrix as a result of crossprod of sparse matrices (by the user jblood94)

is perfect! But I was wondering how I could alter this to produce the tcrossprod rather than the crossprod.

I tried to simply change the crosspod step to tcrosspod and I also tried to transpose the second matrix but it looks like the dimensions are not the same.

SasLNat
  • 33
  • 3
  • tcrossprod is the same as crossprod of the transpose of the individual matrices. thus `tcrossprod(x,y) == crossprod(t(x), t(y))`. So since you have the matrices, transpose them and use the provided function – Onyambu Jul 19 '23 at 02:13
  • What are the dimensions of your sparse matrices? – jblood94 Jul 19 '23 at 11:28

2 Answers2

1

There is a relationship between tcrossprod and crossprod in that tcrossprod is the same as crossprod of the transpose of the individual matrices. Thus tcrossprod(x,y) == crossprod(t(x), t(y)). So since you have the matrices, transpose them individually and use the provided function

Onyambu
  • 67,392
  • 3
  • 24
  • 53
  • Tried that but it did not work. This is the error I got: Error in h(simpleError(msg, call)) : error in evaluating the argument 'x' in selecting a method for function 'triu': Cholmod error 'A and B inner dimensions must match' at file ../MatrixOps/cholmod_ssmult.c, line 80. – SasLNat Jul 19 '23 at 05:23
  • @SasLNat If there is an issue with dimensions that because your matrices are not compatible. ie `tcrossprod(X, Y) = X %*%t(Y) = t(t(X)) %*% t(Y) = crossprod(t(X) , t(Y))`. Recall `crossprod(A,B) = t(A) %*% B` in your case, you take `A =t(X), B = t(Y)` and you will end up with the same result. Note that if you can do `tcrossprod(X, Y)` you should be able to do `crossprod(t(X), t(Y))` unless of course the function has an issue – Onyambu Jul 19 '23 at 05:35
  • I agree, you are correct! I've changed the original function from https://stackoverflow.com/questions/71972327/sparse-matrix-as-a-result-of-crossprod-of-sparse-matrices/71979186#71979186 and will list it below. – SasLNat Jul 19 '23 at 06:58
1

This is made from modification from the answer from jblood94 from: Sparse Matrix as a result of crossprod of sparse matrices

The final result is a data.table.

library(Matrix)

bigtcrossprod <- function(m, nseg) {
  jmax <- ncol(m)
  
  sumj <- cumsum(as.numeric(jmax:1))
  dtj <- data.table::data.table(
    j = 1:jmax,
    int = sumj %/% (sumj[jmax]/nseg + 1)
  )[
    , .(idx1 = min(j), idx2 = max(j)), int
  ][, idx1:idx2]
  
  result <- data.table::rbindlist(
    lapply(
      1:nseg,
      function(seg) {
        cat("\r", seg) # user feedback
        j1 <- dtj$idx1[seg]
        m2 <- tcrossprod(m[, j1:dtj$idx2[seg], drop = FALSE])
        m2 <- as(m2, "dgTMatrix") # converting to sparse matrix
        data.table::data.table(
          i = m2@i + 1, # adding 1 
          j = m2@j + 1, # adding 1 
          v = m2@x
        )
      }
    )
  )
  
  return(result)
}
SasLNat
  • 33
  • 3