How to Perform Matrix Multiplication in R (With Examples)


You can use the following syntax to perform matrix multiplication in R:

#perform element-by-element multiplication
A * B

#perform matrix multiplication
A %*% B

The following examples show how to use this syntax in practice.

Example 1: Element-by-Element Multiplication

The following code shows how to perform element-by-element multiplication between two matrices in R:

#define matrix A
A <- matrix(c(1, 2, 3, 4), ncol=2)
A

     [,1] [,2]
[1,]    1    3
[2,]    2    4

#define matrix B
B <- matrix(c(5, 6, 7, 8), ncol=2)
B

     [,1] [,2]
[1,]    5    7
[2,]    6    8

#perform element-by-element multiplication
A*B

     [,1] [,2]
[1,]    5   21
[2,]   12   32

Using the * operator, R simply multiplied the corresponding elements in each matrix to produce a new matrix.

Here are the exact calculations that were performed:

  • Position [1, 1]: 1 * 5 = 5
  • Position [1, 2]: 3 * 7 = 21
  • Position [2, 1]: 2 * 6 = 12
  • Position [2, 2]: 4 * 8 = 32

Example 2: Matrix Multiplication

The following code shows how to perform matrix multiplication between two matrices in R:

#define matrix A
A <- matrix(c(1, 2, 3, 4), ncol=2)
A

     [,1] [,2]
[1,]    1    3
[2,]    2    4

#define matrix B
B <- matrix(c(5, 6, 7, 8), ncol=2)
B

     [,1] [,2]
[1,]    5    7
[2,]    6    8

#perform matrix multiplication
A %*% B

     [,1] [,2]
[1,]   23   31
[2,]   34   46

Here are the exact calculations that were performed:

  • Position [1, 1]: 1*5 + 3*6 = 23
  • Position [1, 2]: 1*7 + 3*8 = 31
  • Position [2, 1]: 2*5 + 4*6 = 34
  • Position [2, 2]: 2*7 + 4*8 = 46

Refer to these tutorials for a quick primer on the formulas to use to perform matrix multiplication between matrices of various sizes:

Additional Resources

How to Convert Matrix to Vector in R
How to Plot the Rows of a Matrix in R

Leave a Reply

Your email address will not be published.