w3resource

R Programming: Create two 2x3 matrix and add, subtract, multiply and divide the matrixes

R Programming: Matrix Exercise-5 with Solution

Write a R program to create two 2x3 matrix and add, subtract, multiply and divide the matrixes.

Sample Solution:

R Programming Code:

# Create two 2x3 matrixes.
m1 = matrix(c(1, 2, 3, 4, 5, 6), nrow = 2)
print("Matrix-1:")
print(m1)
m2 = matrix(c(0, 1, 2, 3, 0, 2), nrow = 2)
print("Matrix-2:")
print(m2)

result = m1 + m2
print("Result of addition")
print(result)

result = m1 - m2
print("Result of subtraction")
print(result)

result = m1 * m2
print("Result of multiplication")
print(result)

result = m1 / m2
print("Result of division:")
print(result)

Sample Output:

[1] "Matrix-1:"
     [,1] [,2] [,3]
[1,]    1    3    5
[2,]    2    4    6
[1] "Matrix-2:"
     [,1] [,2] [,3]
[1,]    0    2    0
[2,]    1    3    2
[1] "Result of addition"
     [,1] [,2] [,3]
[1,]    1    5    5
[2,]    3    7    8
[1] "Result of subtraction"
     [,1] [,2] [,3]
[1,]    1    1    5
[2,]    1    1    4
[1] "Result of multiplication"
     [,1] [,2] [,3]
[1,]    0    6    0
[2,]    2   12   12
[1] "Result of division:"
     [,1]     [,2] [,3]
[1,]  Inf 1.500000  Inf
[2,]    2 1.333333    3           

R Programming Code Editor:



Have another way to solve this solution? Contribute your code (and comments) through Disqus.

Previous: Write a R program to access the element at 3rd column and 2nd row, only the 3rd row and only the 4th column of a given matrix.
Next: Write a R program to create a matrix from a list of given vectors.

Test your Programming skills with w3resource's quiz.

What is the difficulty level of this exercise?



Follow us on Facebook and Twitter for latest update.