R – Matrix Multiplication
To perform matrix multiplication in R, use the multiplication operator %*%
. Please note the percentile %
symbols surrounding the arithmetic multiplication operator *
.
In this tutorial, we will learn how to multiply matrices using Matrix Multiplication operator with the help of examples.
Syntax
The syntax of the expression to multiply matrices A
and B
is
A %*% B
The expression returns a matrix. The number of columns in matrix A
must equal the number of rows in matrix B
.
Examples
In the following program, we will create matrices A
and B
; multiply them using the matrix multiplication operator, and store the result in matrix AB
.
example.R
data <- c(1, 2, 3, 0, 1, 2, 0, 0, 1)
A <- matrix(data, nrow = 3, ncol = 3)
data <- c(0, 1, 1, 1, 0, 3, 1, 3, 3)
B <- matrix(data, nrow = 3, ncol = 3)
AB <- A %*% B
print("Matrix A")
print(A)
print("Matrix B")
print(B)
print("Matrix Multiplication Result")
print(AB)
Output
[1] "Matrix A"
[,1] [,2] [,3]
[1,] 1 0 0
[2,] 2 1 0
[3,] 3 2 1
[1] "Matrix B"
[,1] [,2] [,3]
[1,] 0 1 1
[2,] 1 0 3
[3,] 1 3 3
[1] "Matrix Multiplication Result"
[,1] [,2] [,3]
[1,] 0 1 1
[2,] 1 2 5
[3,] 3 6 12
Matrix Multiplication operator can be chained. Therefore, we can multiply multiple matrices in a single expression.
Now, let us take three matrices: A
, B
and C
; and find their product ABC
.
example.R
data <- c(1, 2, 3, 0, 1, 2, 0, 0, 1)
A <- matrix(data, nrow = 3, ncol = 3)
data <- c(0, 1, 1, 1, 0, 3, 1, 3, 3)
B <- matrix(data, nrow = 3, ncol = 3)
data <- c(1, 1, 0, 1, 0, 0, 1, 0, 1)
C <- matrix(data, nrow = 3, ncol = 3)
AB <- A %*% B %*% C
print("Matrix A")
print(A)
print("Matrix B")
print(B)
print("Matrix C")
print(C)
print("Matrix Multiplication Result")
print(AB)
Output
[1] "Matrix A"
[,1] [,2] [,3]
[1,] 1 0 0
[2,] 2 1 0
[3,] 3 2 1
[1] "Matrix B"
[,1] [,2] [,3]
[1,] 0 1 1
[2,] 1 0 3
[3,] 1 3 3
[1] "Matrix C"
[,1] [,2] [,3]
[1,] 1 1 1
[2,] 1 0 0
[3,] 0 0 1
[1] "Matrix Multiplication Result"
[,1] [,2] [,3]
[1,] 1 0 1
[2,] 3 1 6
[3,] 9 3 15
Conclusion
In this R Tutorial, we learned how to perform Matrix Multiplication in R, with the help of examples.