# How to Multiply Vector & Rows of Matrix in R (Example Code)

On this page you’ll learn how to multiply matrices and arrays in the R programming language.

## Construction of Example Data

example_matrix <- matrix(c(1, 1, 1, # Creating matrix 2, 2, 2, 3, 3, 3), nrow = 3) example_matrix # Printing matrix # [,1] [,2] [,3] # [1,] 1 2 3 # [2,] 1 2 3 # [3,] 1 2 3 |

example_matrix <- matrix(c(1, 1, 1, # Creating matrix 2, 2, 2, 3, 3, 3), nrow = 3) example_matrix # Printing matrix # [,1] [,2] [,3] # [1,] 1 2 3 # [2,] 1 2 3 # [3,] 1 2 3

example_vector <- 1:3 # Creating vector example_vector # Printing vector # 1 2 3 |

example_vector <- 1:3 # Creating vector example_vector # Printing vector # 1 2 3

## Example: Matrix Multiplication by Vector Based On sweep() Function

sweep(example_matrix, # Applying sweep function in R MARGIN = 2, example_vector, `*`) # [,1] [,2] [,3] # [1,] 1 4 9 # [2,] 1 4 9 # [3,] 1 4 9 |

sweep(example_matrix, # Applying sweep function in R MARGIN = 2, example_vector, `*`) # [,1] [,2] [,3] # [1,] 1 4 9 # [2,] 1 4 9 # [3,] 1 4 9