Linear Algebra with Sage

<Cramer's Rule>

Made by SKKU Linear Algebra Lab (2011)

Solve following LSE using Cramer's Rule.

$\left\{ \begin{array}{ll} x+y+2z=9\\ 2x+4y-3z=1\\ 3x+6y-5z=0 \end{array}\right.$

<Cramer's Rule>

If $A \textbf{x} = \textbf{v}$ is a LSE in $n$ unknowns, then the system has a unique solution iff det$(A)\neq 0$, in which case the solution is

$x_1 = \Large{\frac{det(A_{1})}{det(A)}}$,   $x_2 = \Large{\frac{det(A_{2})}{det(A)}}$,   $\ldots$,   $x_n = \Large{\frac{det(A_{n})}{det(A)}}$

where $A_j$ is the matrix that results when the $j$-th column of $A$ is replaced by $\textbf{v}$.

Define matrices (계수행렬과 상수행렬 생성 및 확인)

 A=matrix([[1,1,2],[2,4,-3],[3,6,-5]]); v=matrix(3,1,[9,1,0]); print A print v

[ 1  1  2]

[ 2  4 -3]

[ 3  6 -5]







Check det$(A)\neq 0$ (주어진 LSE가 Unique Solution을 갖는지 $A$의 행렬식을 구하여 확인)

 det(A)==0

False

Define a function sub(M, col, v) to use Cramer's Rule

M: The Matrix replaced by v

col: The column of M replaced by v

v: replacing vector

(Define a new function in SAGE is helpful when we handle the large size data)

 def sub(M,col,v):     n1=M.nrows()     n2=M.ncols()     S=matrix(n1,n2)       # Define a matrix S which has same size with M     for i in range(n1):       for j in range(n2):         S[i,j]=M[i,j]       # S: copy all entries of M     for i in range(n1):       S[i,col-1]=v[i,0]    # Replacing j-th column of S by v     return S

A1: obtained by replacing the 1st column with the column vector $\textbf{v}$

 A1=sub(A,1,v); A1

[ 9  1  2]

[ 1  4 -3]

[ 0  6 -5]

A2: obtained by replacing the 2nd column with the column vector $\textbf{v}$

 A2=sub(A,2,v); A2

[ 1  9  2]

[ 2  1 -3]

[ 3  0 -5]

A3: obtained by replacing the 3rd column with the column vector $\textbf{v}$

 A3=sub(A,3,v); A3

[1  1  9]

[2  4  1]

[3  6  0]

Find solution of LSE using Cramer's Rule. (크래머 공식을 이용한 풀이)

 det(A1)/det(A), det(A2)/det(A), det(A3)/det(A)

(1, 2, 3)