To perform matrix addition 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, adding 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 add matrix1
and matrix2
. The addition is performed element-wise.result_matrix
.result_matrix
to standard output to see the result of the matrix addition.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,] 6 10 [2,] 8 12
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 add matrix1
and matrix2
. The addition is performed element-wise.result_matrix
.result_matrix
to standard output to see the result of the matrix addition.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,] 11 17 23 [2,] 13 19 25 [3,] 15 21 27
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 add matrix1
and matrix2
. The addition is performed element-wise.result_matrix
.result_matrix
to standard output to see the result of the matrix addition.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,] 18 26 34 42 [2,] 20 28 36 44 [3,] 22 30 38 46 [4,] 24 32 40 48
In this tutorial, we learned How to do Matrix Addition in R language with well detailed examples.