Created
November 5, 2016 17:26
-
-
Save nicholaskajoh/44964e98a5a556230a38e080262c50ff to your computer and use it in GitHub Desktop.
Matrix Calculator using Numpy
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# matrix calculator | |
import numpy as np | |
if __name__ == "__main__": | |
# select matrix dimemsion | |
print("#### MATRIX CALCULATOR ####") | |
print("Paper work: ") | |
print("-- Separate row elements by spaces") | |
print("-- Use x to end matrix input") | |
print("-- Use only nxn matrices for non-arithmetic operations") | |
print() | |
op = int(input("Operation: arithmetic=0, determinant=1, inverse=2: ")) | |
if op == 0: # arithmetic ops | |
# matrix A | |
print("matA: ") | |
matA = [] | |
ar = input() # A row | |
while ar != "x": | |
r = list(map(int, ar.split())) | |
matA.append(r) | |
ar = input() | |
# operator | |
print("Operator: +, -, *") | |
optr = input() | |
# matrix B | |
print("matB: ") | |
matB = [] | |
br = input() # B row | |
while br != "x": | |
r = list(map(int, br.split())) | |
matB.append(r) | |
br = input() | |
try: | |
np_matA = np.matrix(matA) | |
np_matB = np.matrix(matB) | |
# operations | |
if optr == '+': | |
result = np_matA + np_matB | |
elif optr == '-': | |
result = np_matA - np_matB | |
elif optr == '*': | |
result = np_matA * np_matB | |
else: | |
print("Invalid operator!") | |
except: | |
print("Error: Invalid/unconformable matrix/matrices!") | |
raise | |
# result | |
print("Ans: ") | |
[print(str(r)[1:-1]) for r in result] | |
else: | |
# matrix | |
print("mat: ") | |
mat = [] | |
rw = input() # row | |
while rw != "x": | |
r = list(map(int, rw.split())) | |
mat.append(r) | |
rw = input() | |
try: | |
if op == 1: # determinant | |
result = np.linalg.det(mat) | |
print("Ans: ", result) | |
elif op == 2: # inverse | |
result = np.linalg.inv(mat) | |
print("Ans: ") | |
[print(str(r)[1:-1]) for r in result] | |
except: | |
print("Error: Invalid/unconformable matrix!") | |
raise |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment