mult_mat | R Documentation |
Multiply element-wise the rows or columns of a matrix times a vector.
mult_mat(vectorv, matrixv, byrow = TRUE)
vector |
A numeric vector. |
matrix |
A numeric matrix. |
byrow |
A Boolean argument: if |
The function mult_mat()
multiplies element-wise the rows or columns
of a matrix times a vector.
If byrow = TRUE
(the default), then function mult_mat()
multiplies the rows of the argument matrix
times the argument
vector
.
Otherwise it multiplies the columns of matrix
.
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()
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()
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).
A matrix equal to the product of the elements of
matrix
times vector
, with the same dimensions as the
argument matrix
.
## 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++
matrixp <- HighFreq::mult_mat(vectorv, matrixv, byrow=TRUE)
all.equal(matrixr, matrixp)
# Compare the speed of Rcpp with R code
library(microbenchmark)
summary(microbenchmark(
Rcpp=HighFreq::mult_mat(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++
matrixp <- HighFreq::mult_mat(vectorv, matrixv, byrow=FALSE)
all.equal(matrixr, matrixp)
# Compare the speed of Rcpp with R code
library(microbenchmark)
summary(microbenchmark(
Rcpp=HighFreq::mult_mat(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.