Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Fastest way for multiplying a matrix to a vector

Tags:

r

I have a matrix mat and a vector v. I would like to multiply first column of matrix matby 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 
like image 765
rose Avatar asked Aug 21 '13 04:08

rose


People also ask

What is the fastest way to do matrix multiplication?

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.

What is the complexity of multiplying a matrix to a vector?

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).

Can you multiply a vector by a matrix?

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.


1 Answers

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
like image 96
John Avatar answered Sep 21 '22 14:09

John