In R, you can perform matrix addition and subtraction using the + and - operators, respectively. The matrices being operated on must have the same dimensions (i.e., the same number of rows and columns).
Here's an example to illustrate matrix addition and subtraction in R:
# Create two matrices
matrix1 <- matrix(c(1, 2, 3, 4), nrow = 2)
matrix2 <- matrix(c(5, 6, 7, 8), nrow = 2)
# Perform matrix addition
addition_result <- matrix1 + matrix2
# Perform matrix subtraction
subtraction_result <- matrix1 - matrix2
# Print the results
print(addition_result)
print(subtraction_result)
Output:
[,1] [,2]
[1,] 6 10
[2,] 9 12
[,1] [,2]
[1,] -4 -4
[2,] -3 -4
In the example above, we created two 2x2 matrices named matrix1 and matrix2. We then performed matrix addition using the + operator and matrix subtraction using the - operator. The resulting matrices, addition_result and subtraction_result, are printed to the console.
Note that for matrix addition and subtraction to be possible, the matrices must have the same dimensions. If the matrices have different dimensions, R will produce an error.