How to Multiply a Matrix by a Vector in R

R Guides

This tutorial explains how to multiply a matrix by a vector in R.

Multiplying a Matrix by a Vector

Consider the following code that generates a matrix and a vector in R:

#Create a vector of numbers 1, 2, 3
vector <- c(1:3)
vector
# [1] 1 2 3
#create a matrix with three columns and five rows
matrix <- as.matrix(cbind(a = 1:5, b = 6:10, c= 11:15))
matrix
#      a b c
# [1,] 1 6 11
# [2,] 2 7 12
# [3,] 3 8 13
# [4,] 4 9 14
# [5,] 5 10 15

Suppose we want to multiply the matrix by the vector such that we get a new matrix with the following values:

(1*1 + 6*2 + 11*3)    = 46
(2*1 + 7*2 + 12*3)    = 52
(3*1 + 8*2 + 13*3)    = 58
(4*1 + 9*2 + 14*3)    = 64
(5*1 + 10*2 + 15*3) = 70

To perform this type of element-wise multiplication in R, we can simply use the %*% operator:

#multiply the matrix by the vector
matrix %*% vector

#     [,1]
# [1,] 46
# [2,] 52
# [3,] 58
# [4,] 64
# [5,] 70

The end result is a 5×1 matrix.

 

Leave a Reply

Your email address will not be published. Required fields are marked *