To perform matrix subtraction in R, you can use the -
operator. Both matrices must have the same dimensions, meaning the same number of rows and columns. The operation is performed element-wise, subtracting corresponding elements from the two matrices.
In this example,
matrix1
with values from 1 to 4 arranged in 2 rows and 2 columns using the matrix()
function.matrix2
with values from 5 to 8 arranged in 2 rows and 2 columns using the matrix()
function.-
operator to subtract matrix2
from matrix1
. The subtraction is performed element-wise.result_matrix
.result_matrix
to standard output to see the result of the matrix subtraction.matrix1 <- matrix(1:4, nrow = 2, ncol = 2)
matrix2 <- matrix(5:8, nrow = 2, ncol = 2)
result_matrix <- matrix1 - matrix2
print(result_matrix)
[,1] [,2] [1,] -4 -4 [2,] -4 -4
In this example,
matrix1
with values from 1 to 9 arranged in 3 rows and 3 columns using the matrix()
function.matrix2
with values from 10 to 18 arranged in 3 rows and 3 columns using the matrix()
function.-
operator to subtract matrix2
from matrix1
. The subtraction is performed element-wise.result_matrix
.result_matrix
to standard output to see the result of the matrix subtraction.matrix1 <- matrix(1:9, nrow = 3, ncol = 3)
matrix2 <- matrix(10:18, nrow = 3, ncol = 3)
result_matrix <- matrix1 - matrix2
print(result_matrix)
[,1] [,2] [,3] [1,] -9 -9 -9 [2,] -9 -9 -9 [3,] -9 -9 -9
In this example,
matrix1
with values from 1 to 16 arranged in 4 rows and 4 columns using the matrix()
function.matrix2
with values from 17 to 32 arranged in 4 rows and 4 columns using the matrix()
function.-
operator to subtract matrix2
from matrix1
. The subtraction is performed element-wise.result_matrix
.result_matrix
to standard output to see the result of the matrix subtraction.matrix1 <- matrix(1:16, nrow = 4, ncol = 4)
matrix2 <- matrix(17:32, nrow = 4, ncol = 4)
result_matrix <- matrix1 - matrix2
print(result_matrix)
[,1] [,2] [,3] [,4] [1,] -16 -18 -20 -22 [2,] -16 -18 -20 -22 [3,] -16 -18 -20 -22 [4,] -16 -18 -20 -22
In this tutorial, we learned How to do Matrix Subtraction in R language with well detailed examples.