9 Matrix Algebra
9 Matrix Algebra
x[i] = B[i]/A[i,i]
return x
x=back_sub(A,B)
print(A)
print(B)
print(x)
#converting a matrix into lower triangular one for forward substitution
A=np.array([4,8,4,0,1,5,4,-3,1,4,7,2,1,3,0,-2],dtype=float).reshape(4,4)
B=np.array([8,-4,10,-4],dtype=float).reshape(4,1)
#finding lower triangular matrix for forward substitution
1
def lower_matrix1D(A,B):
for j in range(3,0,-1):
for i in range(0,j):
B[i]=B[i]-B[j]*(A[i,j]/(A[j,j]))
A[i,:]=A[i,:]-A[j,:]*(A[i,j]/(A[j,j]))
return B
def lower_matrix2D(A):
for j in range(3,0,-1):
for i in range(0,j):
A[i,:]=A[i,:]-A[j,:]*(A[i,j]/(A[j,j]))
return A
def for_sub(A,B):
x = np.zeros(4)
for i in range(0,4): #this refers to the rows; i goes 2,1,0
for j in range(0,i): #j goes 1,2 @ i = 0
#j goes 2 @ i = 1
B[i] = B[i] - A[i,j]*x[j]
x[i] = B[i]/A[i,i]
return x
B=lower_matrix1D(A,B)
A=lower_matrix2D(A)
x=for_sub(A,B)
print(A)
print(B)
print(x)
[[ 4. 8. 4. 0.]
[ 1. 5. 4. -3.]
[ 1. 4. 7. 2.]
[ 1. 3. 0. -2.]]
[[ 4. 8. 4. 0.]
[ 0. 3. 3. -3.]
[ 0. 0. 4. 4.]
[ 0. 0. 0. 1.]]
[[12.]
[-3.]
[ 4.]
[ 2.]]
[ 3. -1. 1. 2.]
[[ 0.97959184 0. 0. 0. ]
[-1.64285714 -3.5 0. 0. ]
[ 2. 7. 7. 0. ]
[ 1. 3. 0. -2. ]]
[[ 2.93877551]
[ 3.5 ]
[ 7. ]
[-4. ]]
2
[ 3. -1. 1. 2.]
[[ 1. 0. 0. 0. ]
[ 0.25 1. 0. 0. ]
[ 0.25 0.66666667 1. 0. ]
[ 0.25 0.33333333 -0.5 1. ]]
[[ 4. 8. 4. 0.]
[ 0. 3. 3. -3.]
[ 0. 0. 4. 4.]
[ 0. 0. 0. 1.]]
[ 3. -1. 1. 2.]
3
B3=B.reshape(4,1)
print(A3)
print(B3)
I=np.array([1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1],dtype=float).reshape(4,4)
L=np.array([1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1],dtype=float).reshape(4,4)
def lu(A):
for j in range (0,4):
for i in range(j+1,4):
L[i,:]=L[i,:]+I[j,:]*(A[i,j]/A[j,j])
A[i,:]=A[i,:]-A[j,:]*(A[i,j]/A[j,j])
return L
def LU(A3,B3):
y=for_sub(lu(A3),B3)
U=upper_matrix2D(A3)
return back_sub(U,y)
print(LU(A3,B3))
#1st method
def backward(A,B):
B11=upper_matrix1D(A,B)
A11=upper_matrix2D(A)
return back_sub(A11,B11)
print(backward(A1,B1))
4
[[ 8.]
[-4.]
[10.]
[-4.]]
[[ 4. 8. 4. 0.]
[ 1. 5. 4. -3.]
[ 1. 4. 7. 2.]
[ 1. 3. 0. -2.]]
[[ 8.]
[-4.]
[10.]
[-4.]]
[ 3. -1. 1. 2.]
[ 3. -1. 1. 2.]
In [143]: A=np.zeros(16)
for i in range(0,16):
A[i]=int(input("enter %ith element:"%(i+1)))
A1=A.reshape(4,4)
B=np.zeros(4)
for i in range(0,4):
B[i]=int(input("enter %ith element:"%(i+1)))
B1=B.reshape(4,1)
print(A1)
print(B1)
#2nd method
A2=A.reshape(4,4)
B2=B.reshape(4,1)
print(A2)
print(B2)
def forward(A2,B2):
B22=lower_matrix1D(A2,B2)
A22=lower_matrix2D(A2)
return for_sub(A22,B22)
print(forward(A2,B2))
[ 3. -1. 1. 2.]
In [152]: A=np.array([4,8,4,0,1,5,4,-3,1,4,7,2,1,3,0,-2],dtype=float).reshape(4,4)
B=np.array([8,-4,10,-4],dtype=float).reshape(4,1)
LU(A,B)
In [153]: backward(A,B)
5
In [155]: A=np.array([4,8,4,0,1,5,4,-3,1,4,7,2,1,3,0,-2],dtype=float).reshape(4,4)
B=np.array([8,-4,10,-4],dtype=float).reshape(4,1)
forward(A,B)