In: Computer Science
This exercise allows a user to enter the values of two, 3x3 matrices and then select from options including, addition, subtraction, matrix multiplication, and element by element multiplication. You should use numpy.matmul() for matrix multiplication (e.g. np.matmul(a, b) ). The program should computer the appropriate results and return the results, the transpose of the results, the mean of the rows for the results, and the mean of the columns for the results. When entering data you should check that each value is numeric for the matrices. The user interface should continue to run until the user indicates they are ready to exit.
If an inappropriate entry is detected, the program should prompt for a correct value and continue to do so until a correct value is entered. Hints: 1. Use numpy and associated functionality 2. Create and use functions as often as possible 3. Use comments to document your code 4. Both integers and float values are acceptable
import numpy as np def checkEntry(inputValue): try: float(inputValue) except ValueError: return False return True def getMatrix(): mat = np.zeros((3, 3)) for row in range(3): for column in range(3): check = False while not check: num = input('Enter element at position ({:d},{:d}): '.format(row + 1, column + 1)) check = checkEntry(num) if not check: print('Please enter a numeric value!') mat[row, column] = float(num) print() return mat print('Enter first matrix: ') mat1 = getMatrix() print('Enter second matrix: ') mat2 = getMatrix() print('Enter option:\n1.Addition\n2.Subtraction\n3.Matrix multiplication\n4.Element by element multiplication\n5.Exit') choice = int(input()) while choice != 5: if choice == 1: res = mat1 + mat2 elif choice == 2: res = mat1 - mat2 elif choice == 3: res = np.matmul(mat1, mat2) elif choice == 4: res = np.multiply(mat1, mat2) print('Result:') print(res) print('Transpose of result:') print(res.T) print('Mean of rows:') print(np.mean(res, 1)) print('Mean of columns:') print(np.mean(res, 0)) print('\nEnter option:\n1.Addition\n2.Subtraction\n3.Matrix multiplication\n4.Element by element multiplication\n5.Exit') choice = int(input())