# Matrix In R - Arithmetic Operations / Addition And Subtraction On Matrices In R

## Introduction

**In my previous articles, we all have seen what a matrix is and how to create matrices in R. We have also seen how to rename matrix rows and columns, and how to add rows and columns, etc. Now, we shall learn and discuss how to perform arithmetic operations like addition and subtraction on two matrices in R. We shall also see how it works, using examples in R Studio. **

**Step 1 - Creating Two Different Matrices**

- #Creating First matrix
- myMatrixA <- matrix(data = 1:9, nrow = 3, ncol = 3)
- myMatrixA

**Output **> myMatrixA

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

[1,] 1 4 7

[2,] 2 5 8

[3,] 3 6 9

- #Creating Second matrix
- myMatrixB <- matrix(data = 1:9, nrow = 3, ncol = 3)
- myMatrixB

**Output **> myMatrixB

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

[1,] 1 4 7

[2,] 2 5 8

[3,] 3 6 9
The above operation of creating two matrices has been shown in the below images.
A matrix is the data element, hence adding matrices is the same as adding two elements in each other. The below code will add the two matrices.

**Step 2 - Performing Arithmetic Operations **So far, we have already created matrices. Now, we can use it for our arithmetic operations on these matrices.**Adding Both Matrices **First of all, we shall perform the addition operation on both matrices. Let's look at the below images first.- #Adding Both Matrices
- myMatrixCAfterAdding <- myMatrixA + myMatrixB
- myMatrixCAfterAdding

**Output **> myMatrixCAfterAdding

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

[1,] 2 8 14

[2,] 4 10 16

[3,] 6 12 18
It looks as below in R Studio while adding both the matrices.
We have already done the addition of two matrices. Now, let us visualize how it has performed the addition operation, using the below images. In the below images, the same color pattern has been used to highlight the element at the same position in both the matrices. For example, the yellow color has been used to highlight the element of the first row and the first column in both matrices.
We can see that in addition to operation, the elements with the same index are added to each other. After addition, the dimension is also the same as it was, i.e., 3 rows and 3 columns.

**Subtracting of Matrices **Subtraction of matrices behaves almost the same as it behaves in the case of the addition of two matrices in R. The below code shows how to perform the subtraction operations in matrices in R.- #Subtracting Matrix
- myMatrixCAfterSubtraction <- myMatrixA - myMatrixB
- myMatrixCAfterSubtraction

**Output **> myMatrixCAfterSubtraction

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

[1,] 0 0 0

[2,] 0 0 0

[3,] 0 0 0
As we can see after subtraction, all the elements of the output matrix are 0 because elements of both matrices were the same in the same position.

## Summary

**In this article, we have seen how to perform simple arithmetic operations on matrices in R. We have seen and visualized the addition and subtraction operation on matrices in R. **