-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathP2 Inveret a matrix by LU decomposition.py
86 lines (61 loc) · 1.38 KB
/
P2 Inveret a matrix by LU decomposition.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
import numpy as np
def LU_decomposition(A,l,i,j):
n,m = A.shape
for x in range(i,n):
if A[x,j] != 0 :
break
else :
return A
if x >i :
A[[x, i]] = A[[i, x]]
l[i:,j:j+1] = A[i:,j:j+1]/A[i,j]
A[i+1:] -=( A[i]/A[i,j] * A[i+1:,j:j+1])
return A,l
def forsubs(l,b):
n,m= l.shape
l = np.hstack((l, b))
for i in range(0,n-1):
j=i
l[i+1:,-1] -= l[i+1,j] * l[i,-1]
y = l[:,-1]
y = y.reshape((n,1))
return y
def backsubs(u,y):
n,m= u.shape
u= np.hstack((u, y))
for i in range(n-1,-1,-1):
j=i
u[i,-1] /=u[i,j]
if i != 0:
u[:i,-1] -= (u[:i,j] * u[i,-1])
x = u[:,-1]
x = x.reshape((n,1))
return x
n=int(input("Enter the matrix size : "))
A=np.zeros((n,n))
l = np.zeros((n,n))
print("\n enter the matrix: \n")
for i in range(n):
A[i] =input().split(" ")
for t in range(0,n):
A,l = LU_decomposition(A,l,t,t)
print(" matrix U: ")
print(A)
print()
print("".center(20,"*"))
print()
print(" matrix L: ")
print(l)
print()
print("".center(20,"*"))
print()
reverseA = np.zeros((n,n))
e = np.zeros((n,1))
for i in range(0,n):
e[i] = 1
y = forsubs(l,e)
reverseA[:,i:i+1]= backsubs(A,y)
e[i]=0
print("".center(20,"*"))
print("reverse matrix: ")
print(reverseA)