Multiply Rows of Matrix by Vector in R (Example)


This article explains how to do a matrix multiplication with a vector in the R programming language.

The tutorial will contain these content blocks:

Here’s the step-by-step process:


Creating Exemplifying Data

Let’s first construct some example data.

my_mat <- matrix(1:12, nrow = 3)          # Example matrix
my_mat                                    # Print matrix
#      [,1] [,2] [,3] [,4]
# [1,]    1    4    7   10
# [2,]    2    5    8   11
# [3,]    3    6    9   12

As you can see based on the previous output of the RStudio console, the example data is a matrix with three rows and four columns.

Let’s also create an example vector (or array):

my_vec <- 1:4                             # Example vector
my_vec                                    # Print vector
# 1 2 3 4

Our example vector contains of four numeric values ranging from 1 to 4.


Example: Multiply Matrix by Vector Using sweep Function

The following R programming syntax shows how to use the sweep function to multiply every row of our matrix with our example vector.

sweep(my_mat, MARGIN = 2, my_vec, `*`)    # Apply sweep
#      [,1] [,2] [,3] [,4]
# [1,]    1    8   21   40
# [2,]    2   10   24   44
# [3,]    3   12   27   48

Have a look at the previous output: We multiplied the lines of our matrix with our vector.


Video & Further Resources

Would you like to know more about matrix multiplication in R? Then you might watch the following video of my YouTube channel. In the video, I explain the R programming code of this tutorial.


The YouTube video will be added soon.


In addition, you may want to have a look at some of the related articles on this homepage:


Summary: In this tutorial you learned how to multiply matrices and arrays in the R programming language. If you have additional questions, tell me about it in the comments section.


Leave a Reply

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

Fill out this field
Fill out this field
Please enter a valid email address.