Computer Science, asked by Anonymous, 6 hours ago

Write a program in python to add subtract and multiply two matrices. These matrices can be of any greed such as 2 × 2 or 2 × 3 or 3 × 3 or 3 × 2 etc.

I am giving 36 points and expecting good answer.​

Answers

Answered by anindyaadhikari13
5

Solution.

The given co‎‎de is written in Python.

import numpy as np

def displayMatrix(a):

   for i in a:

       print('  '.join(str(x) for x in i))

def inputMatrix(rows,cols):

   A=[]

   for i in range(rows):

       X=[]

       for j in range(cols):

           X.append(eval(input('>>')))

       A.append(X)

   return A

a=int(input('Enter the number of rows for the first matrix: '))

b=int(input('Enter the number of cols for the first matrix: '))

print('Enter the matrix items..')

A=inputMatrix(a,b)

print('----------------------------------')

c=int(input('Enter the number of rows for the second matrix: '))

d=int(input('Enter the number of cols for the second matrix: '))

print('Enter the matrix items..')

B=inputMatrix(c,d)

print('----------------------------------')

print('1. Addition.')

print('2. Subtraction.')

print('3. Multiplication.')

choice=int(input('Enter your choice: '))

try:

   if choice==1:

       if a==c and b==d:

           C=np.add(A,B)

       else:

           raise Exception

       print('Sum of the matrix is:')

       displayMatrix(C)

   elif choice==2:

       if a==c and b==d:

           C=np.subtract(A,B)

       else:

           raise Exception

       print('Difference of the matrix is:')

       displayMatrix(C)

   elif choice==3:

       C=np.dot(A,B)

       print('Product of the matrix is:')

       displayMatrix(C)

   else:

       print('Invalid Choice.')

except:

   print('Sorry but the operation cannot be performed.')

Explanation.

  • The problem is solved using numpy module. We have two matrices and we have to perform matrix addition, subtraction and multiplication.
  • Numpy module has functions add(), subtract() and dot() which can be used to add subtract and multiply matrices. The displayMatrix() method is used to display 2d array in matrix form.

anindyaadhikari13: Thanks for the brainliest ^_^
Similar questions