Introduction
- #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.
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.
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.


- #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.

Raushan KumarPosted Dec 5, 2020, 2:32 AM
Really great. Concepts are very clearly spelt out particularly examples
Sumit RajguruPosted Aug 16, 2018, 4:18 AM
Nice one. Keep it up
Abhishek MishraPosted Aug 13, 2018, 9:47 AM
Trust me I was waiting for your next one in R. Thanks for the series. This is being used by few folks whom I have forwarded who cannot afford to pay hefty amount in coaching institutes. Thanks for the series.