
Numerical Techniques:
Solving Sets of
Equations - Linear
Algebra and Matrix
Computing II
Dr. Cem Özdo
˘
gan
LOGIK
Using the LU Matrix for
Multiple Right-Hand Sides
The Inverse of a Matrix
Eigenvalues and
Eigenvectors of a Matrix
Normal Modes of Coupled
Oscillation
Iterative Methods
Jacobi Method
11.9
Using th e LU Matrix for Multiple Right-Hand Sides III
Phyton Code:
1 impo rt numpy as np
2 from s cip y . l i n a l g im por t lu
3 A = np . a r ra y ([ [ 0 . 0 , 2. 0 , 0 . 0 , 1 . 0 ] , [ 2 . 0 , 2.0 , 3 . 0 , 2 . 0] , [ 4 . 0 , −3.0, 0. 0 , 1 . 0] , [ 6 . 0 , 1. 0 ,
−6.0, − 5.0] ])
4 P , L , U = l u (A)
5 p r i n t ( " SciPy LU−decomposition : P − P ermu tation Mat r ix \ n" , P)
6 p r i n t ( " SciPy LU−decomposition : L − Lower T r i a n g u l a r wit h u n i t di ag on a l elements \ n" , L )
7 p r i n t ( " SciPy LU−decomposition : U − Upper T r i a n g u la r \ n " , U)
8 def f orward ( L , b ) :
9 y=np . ze ros ( np . shape ( b ) , dt ype= f l o a t )
10 f o r i in range ( len ( b ) ) :
11 y [ i ]=np . copy ( b [ i ] )
12 f o r j i n range ( i ) :
13 y [ i ] = y [ i ]−(L [ i , j ]
*
y [ j ] )
14 y [ i ] = y [ i ] / L [ i , i ]
15 re t ur n y
16 b = np . arr a y ( [ [ 6 . 0 ] , [ − 7. 0] , [ − 2.0] , [ 0 . 0 ] ] )
17 # b = np . ar ray ( [ [ 1 . 0 ] , [ 4 . 0 ] , [ − 3.0] , [ 1 . 0 ] ] )
18 y=forward ( L , b)
19 p r i n t ( " y ve ct o r from Ly=b by forward s u b s t i t u t i o n : " , np . t ranspose ( y ) )
20 de f backward (U, y) :
21 x=np . zeros ( np . shape ( y ) ,dtype= f l o a t )
22 yl en = le n ( y )−1
23 x [ yle n ] =y [ ylen ] /U [ y len , yle n ] # P r i n t the l a s t stage x value
24 f o r i in range ( y len −1,−1,−1):
25 x [ i ]=np . copy ( y [ i ] )
26 f o r j i n range ( ylen , i ,−1) :
27 x [ i ] = x [ i ]−(U[ i , j ]
*
x [ j ] )
28 x [ i ] = x [ i ] / U[ i , i ]
29 r et u rn x
30 x=backward (U, y )
31 p r i n t ( " x ve ct o r from Ux=y by b ackward s u b s t i t u t i o n : " , np . transpose ( x ) )