Open In App

Create Two 2×3 Matrix and Add, Subtract, Multiply and Divide the Matrixes in R

Last Updated : 02 Jun, 2022
Improve
Improve
Like Article
Like
Save
Share
Report

In this article, we will create two matrices with 2 rows and 3 columns each, then add, subtract, multiply and divide these two matrices in R Programming language.

We can create rows and columns in a matrix by using nrow and ncol parameters, nrow specifies the number of rows and ncol specifies the number of columns present in the matrix.

Syntax: matrix(data,nrow,ncol)

Sample Input:

 [,1] [,2] [,3]
[1,]    3    5    3
[2,]    4    2    4
     [,1] [,2] [,3]
[1,]    3    2    8
[2,]    4    7    9

Sample Output:
 "Addition"
 
     [,1] [,2] [,3]
[1,]    6    7   11
[2,]    8    9   13

 "Subtraction"
 
     [,1] [,2] [,3]
[1,]    0    3   -5
[2,]    0   -5   -5

"Multiplication"

     [,1] [,2] [,3]
[1,]    9   10   24
[2,]   16   14   36

"Division"

     [,1]      [,2]      [,3]
[1,]    1 2.5000000 0.3750000
[2,]    1 0.2857143 0.4444444

Example:

R program to create two matrices with 2 rows and 2 column each and display.

R




# create first matrix
first = matrix(c(3,4,5,2,3,4), nrow = 2,ncol=3)
  
# create second matrix
second = matrix(c(3,4,2,7,8,9), nrow = 2,ncol=3)
  
# display 
print(first)
  
print(second)


Output:

 

We can perform addition using + operator, subtraction using – opertaor, division using the / operator,the  and multiplication using * operator. Each number in a row/column in first matrix is operated with other elements in the second element in the same position.

Example:

In this example, we are doing the above operations on the above matrices.

R




# create first matrix
first = matrix(c(3,4,5,2,3,4), nrow = 2,ncol=3)
  
# create second matrix
second = matrix(c(3,4,2,7,8,9), nrow = 2,ncol=3)
  
print("Addition")
  
# add 2 matrices
print(first+second)
  
print("Subtraction")
  
# subtract2 matrices
print(first-second)
  
print("Multiplication")
  
# multiply 2 matrices
print(first*second)
  
print("Division")
  
# divide 2 matrices
print(first/second)


Output:

 



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads