SparseMatrix-mult: SparseMatrix multiplication and cross-product

SparseMatrix-multR Documentation

SparseMatrix multiplication and cross-product

Description

Like ordinary matrices in base R, SparseMatrix derivatives can be multiplied with the %*% operator. They also support crossprod() and tcrossprod().

Value

The %*%, crossprod() and tcrossprod() methods for SparseMatrix objects always return an ordinary matrix of type() "double".

Note

Matrix multiplication and cross-product of SparseMatrix derivatives are multithreaded. See set_SparseArray_nthread for how to control the number of threads.

See Also

  • %*% and crossprod in base R.

  • SparseMatrix objects.

  • S4Arrays::type in the S4Arrays package to get the type of the elements of an array-like object.

  • Ordinary matrix objects in base R.

Examples

m1 <- matrix(0L, nrow=15, ncol=6)
m1[c(2, 6, 12:17, 22:33, 55, 59:62, 90)] <- 101:126
svt1 <- as(m1, "SVT_SparseMatrix")

set.seed(333)
svt2 <- poissonSparseMatrix(nrow=6, ncol=7, density=0.2)

svt1 %*% svt2
m1   %*% svt2

## Unary crossprod() and tcrossprod():
crossprod(svt1)               # same as t(svt1) %*% svt1
tcrossprod(svt1)              # same as svt1 %*% t(svt1)

## Binary crossprod() and tcrossprod():
crossprod(svt1[1:6, ], svt2)  # same as t(svt1[1:6, ]) %*% svt2
tcrossprod(svt1, t(svt2))     # same as svt1 %*% svt2

## Sanity checks:
m12 <- m1 %*% as.matrix(svt2)
stopifnot(
  identical(svt1 %*% svt2, m12),
  identical(m1 %*% svt2, m12),
  identical(crossprod(svt1), t(svt1) %*% svt1),
  identical(tcrossprod(svt1), svt1 %*% t(svt1)),
  identical(crossprod(svt1[1:6, ], svt2), t(svt1[1:6, ]) %*% svt2),
  identical(tcrossprod(svt1, t(svt2)), m12)
)

Bioconductor/SparseArray documentation built on Oct. 30, 2024, 12:14 p.m.