Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Multiply rows of matrix by vector?

I have a numeric matrix with 25 columns and 23 rows, and a vector of length 25. How can I multiply each row of the matrix by the vector without using a for loop?

The result should be a 25x23 matrix (the same size as the input), but each row has been multiplied by the vector.

Added reproducible example from @hatmatrix's answer:

matrix <- matrix(rep(1:3,each=5),nrow=3,ncol=5,byrow=TRUE)       [,1] [,2] [,3] [,4] [,5] [1,]    1    1    1    1    1 [2,]    2    2    2    2    2 [3,]    3    3    3    3    3  vector <- 1:5 

Desired output:

     [,1] [,2] [,3] [,4] [,5] [1,]    1    2    3    4    5 [2,]    2    4    6    8   10 [3,]    3    6    9   12   15 
like image 542
pixel Avatar asked Sep 04 '10 18:09

pixel


People also ask

Can you multiply matrix with vector?

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.

Can you multiply matrix rows?

You can only multiply two matrices if their dimensions are compatible , which means the number of columns in the first matrix is the same as the number of rows in the second matrix.


1 Answers

I think you're looking for sweep().

# Create example data and vector mat <- matrix(rep(1:3,each=5),nrow=3,ncol=5,byrow=TRUE)      [,1] [,2] [,3] [,4] [,5] [1,]    1    1    1    1    1 [2,]    2    2    2    2    2 [3,]    3    3    3    3    3  vec <- 1:5  # Use sweep to apply the vector with the multiply (`*`) function #  across columns (See ?apply for an explanation of MARGIN)  sweep(mat, MARGIN=2, vec, `*`)      [,1] [,2] [,3] [,4] [,5] [1,]    1    2    3    4    5 [2,]    2    4    6    8   10 [3,]    3    6    9   12   15 

It's been one of R's core functions, though improvements have been made on it over the years.

like image 65
hatmatrix Avatar answered Oct 11 '22 11:10

hatmatrix