Home > OS >  numpy matrix inverse input
numpy matrix inverse input

Time:03-23

How can I improve this matrix inverse calculator I made this matrix inverse calculator and it works fine but i want to know how can this program be made shorter.Thanks

 from numpy import *
 
 #inverse calculator
 print(array([['a,b,c'],['d,e,f'],['g,h,i']]))
 
 a = int(input("a: "))
 b = int(input("b: ")) 
 c = int(input("c: "))
 d = int(input("d: ")) 
 e = int(input("e: ")) 
 f = int(input("f: ")) 
 g = int(input("g: ")) 
 h = int(input("h: "))
 i = int(input("i: "))
 
 x = array([[a,b,c],[d,e,f],[g,h,i]])  #we made matrixform
 #print(x)
  
 det = linalg.det(x)  # we take determinant to check if it is 0 or not
 if det != 0:   #if its not 0 then inverse is possible
   inverse = linalg.inv(x)
   print("So the inverse of matrix \n",x, "is \n", inverse)
 else: #if it is 0 then print this:
     print(".\n .\n Matrix is singular,\n Inverse can not be calculated")  

CodePudding user response:

The only way I think it could be shorter is:

x = array([int(input(f"{ch}: ")) for ch in "abcdefghi"]).reshape((3,3))
inverse = linalg.inv(x) if linalg.det(x) != 0 else np.nan  # or False or something else

CodePudding user response:

One way would be just use try-except:

try:
    print(f"inv of matrix {x} is {np.linalg.inv(x)}")
except np.linalg.LinAlgError:
    print("Matrix is singualr")

Output:

x1 = np.array([[1,2,3], [4,5,6], [7,8,9]])
x2 = np.array([[1,2,3], [4,5,6], [7,8,10]])

def is_inversible(x):
    try:
        print(f"inv of matrix \n{x} is \n{np.linalg.inv(x)}")
    except np.linalg.LinAlgError:
        print("Matrix is singualr")

is_inversible(x1)
# Matrix is singualr

is_inversible(x2)
#inv of matrix 
#[[ 1  2  3]
# [ 4  5  6]
# [ 7  8 10]] is 
#[[-0.66666667 -1.33333333  1.        ]
# [-0.66666667  3.66666667 -2.        ]
# [ 1.         -2.          1.        ]]

CodePudding user response:

Here is the better way

import numpy as np

str_inp = input('Enter a b c d e f g h i \n')
elems = list(map(int,str_inp.split()[0:9]))

x = np.array(elems).reshape(3,3)  # we made matrixform
print(x)
try:
    inverse = np.linalg.inv(x)
    print(inverse)
except np.linalg.LinAlgError:
    print('Inverse doesnt exist for the given matrix')

Output


Enter a b c d e f g h i 
1 2 3 4 5 6 7 8 9
[[1 2 3]
 [4 5 6]
 [7 8 9]]
[[ 3.15251974e 15 -6.30503948e 15  3.15251974e 15]
 [-6.30503948e 15  1.26100790e 16 -6.30503948e 15]
 [ 3.15251974e 15 -6.30503948e 15  3.15251974e 15]]

  • Related