mult_mat_ref | R Documentation |
Multiply the rows or columns of a matrix times a vector, element-wise and in place, without copying the data in memory.
mult_mat_ref(vectorv, matrixv, byrow = TRUE)
vectorv |
A numeric vector. |
matrixv |
A numeric matrix. |
byrow |
A Boolean argument: if |
The function mult_mat_ref()
multiplies the rows or columns of a
matrix times a vector, element-wise and in place, without
copying the data in memory.
It accepts a pointer to the argument matrixv
, and it
overwrites the old matrix
values with the new values. It performs
the calculation in place, without copying the matrix in memory,
which can significantly increase the computation speed for large matrices.
If byrow = TRUE
(the default), then function mult_mat_ref()
multiplies the rows of the argument matrixv
times the argument
vectorv
.
Otherwise it multiplies the columns of matrixv
.
In R
, matrix multiplication is performed by columns.
Performing multiplication by rows is often required, for example when
multiplying asset returns by portfolio weights.
But performing multiplication by rows requires explicit loops in R
,
or it requires matrix transpose. And both are slow.
The function mult_mat_ref()
uses RcppArmadillo
C++
code, so when multiplying large matrix columns it's several times
faster than vectorized R
code, and it's even much faster compared
to R
when multiplying the matrix rows.
The function mult_mat_ref()
performs loops over the matrix
rows and columns using the Armadillo
operators each_row()
and each_col()
, instead of performing explicit for()
loops
(both methods are equally fast).
Void (no return value - modifies the data in place).
## Not run:
# Create vector and matrix data
matrixv <- matrix(round(runif(25e4), 2), nc=5e2)
vectorv <- round(runif(5e2), 2)
# Multiply the matrix rows using R
matrixr <- t(vectorv*t(matrixv))
# Multiply the matrix rows using C++
HighFreq::mult_mat_ref(vectorv, matrixv, byrow=TRUE)
all.equal(matrixr, matrixv)
# Compare the speed of Rcpp with R code
library(microbenchmark)
summary(microbenchmark(
Rcpp=HighFreq::mult_mat_ref(vectorv, matrixv, byrow=TRUE),
Rcode=t(vectorv*t(matrixv)),
times=10))[, c(1, 4, 5)] # end microbenchmark summary
# Multiply the matrix columns using R
matrixr <- vectorv*matrixv
# Multiply the matrix columns using C++
HighFreq::mult_mat_ref(vectorv, matrixv, byrow=FALSE)
all.equal(matrixr, matrixv)
# Compare the speed of Rcpp with R code
library(microbenchmark)
summary(microbenchmark(
Rcpp=HighFreq::mult_mat_ref(vectorv, matrixv, byrow=FALSE),
Rcode=vectorv*matrixv,
times=10))[, c(1, 4, 5)] # end microbenchmark summary
## End(Not run)
Add the following code to your website.
For more information on customizing the embed code, read Embedding Snippets.