I have a matrix mat
and a vector v
. I would like to multiply first column of matrix mat
by first element of vector v
and multiply the second column of matrix mat
by second element of vector v
. I can do it as shown. How can I do this faster in R since we get a big matrix?
mat = matrix(rnorm(1500000), ncol= 100)
v= rnorm(100)
> system.time( mat %*% diag(v))
user system elapsed
0.02 0.00 0.02
In linear algebra, the Strassen algorithm, named after Volker Strassen, is an algorithm for matrix multiplication. It is faster than the standard matrix multiplication algorithm for large matrices, with a better asymptotic complexity, although the naive algorithm is often better for smaller matrices.
In terms of serial complexity, the matrix-vector multiplication is qualified as a quadratic complexity algorithm (or a bilinear complexity algorithm if the matrix is rectangular).
To define multiplication between a matrix A and a vector x (i.e., the matrix-vector product), we need to view the vector as a column matrix. We define the matrix-vector product only for the case when the number of columns in A equals the number of rows in x.
Recycling can make it faster but you recycle within columns, not across, so just transpose and transpose back.
t( t(mat) * v )
This should be faster than sweep
or %*%
.
microbenchmark(mat %*% diag(v),sweep(mat, 2, v, FUN = "*"), t(t(mat)*v))
Unit: milliseconds
expr min lq median uq max neval
%*% 150.47301 152.16306 153.17379 161.75416 281.3315 100
sweep 35.94029 42.67210 45.53666 48.07468 168.3728 100
t(t(mat) * v) 16.50813 23.41549 26.31602 29.44008 160.1651 100
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With