기본 콘텐츠로 건너뛰기

[matplotlib] 등고선(Contour)

[Linear Algebra]행렬 연산(matrix operation)

행렬 연산

행렬의 기본연산은 같은 차원들 사이에서 이루어 집니다. 다음은 같은 차원의 두개 또는 세개 행렬들 사이에서 성립되는 관계를 나타낸 것입니다.

  • A, B, C: 행렬, I: 항등행렬 I, r, s: 스칼라
  • A + B = B + A
  • (A + B) + C = A + (B + C)
  • A + 0 = A
  • r(A + B) = rA + rB
  • (r + s)A = rA + sA
  • r(sA) = (rs)A
  • A(BC) = (AB)C
  • A(B + C) = AB + AC
  • (B + C)A = BA + CA
  • r(AB) = (rA)B = A(rC)
  • IA = AI = A
import numpy as np
import scipy.linalg as LA
 from sympy import *

예 1)

행렬 A,B,C에서의 연산

$$A=\begin{bmatrix}4& 0& 5\\-1& 3& 2\end{bmatrix}\quad B=\begin{bmatrix} 1& 1& 1\\3& 5& 7\end{bmatrix} \quad C=\begin{bmatrix}2& -3\\ 0& 1 \end{bmatrix}$$

A=np.mat("4,0,5;-1,3,2")
B=np.mat("1,1,1; 3,5,7")
C=np.mat("2,-3; 0,1")
print(A+B)
[[5 1 6]
 [2 8 9]]
try:
    A+C
except:
    print("행렬의 사칙연산은 동일한 차원에서 실행됩니다.")
행렬의 사칙연산은 동일한 차원에서 실행됩니다.
print(2*B)
[[ 2  2  2]
 [ 6 10 14]]
print(A-2*B)
[[  2  -2   3]
 [ -7  -7 -12]]

행렬곱(matrix product): 행렬들 사이의 각 벡터의 내적을 계산합니다. 연산은 식 1과 같이 이루어집니다.

$$\tag{식 1}\begin{bmatrix}\color{red}a&\color{red}b &\color{red}c\\\color{blue}d & \color{blue}e& \color{blue}f\end{bmatrix} \begin {bmatrix} \color{red}a& \color{blue}d\\ \color{red}b& \color{blue}e\\ \color{red}c&\color{blue}f \end{bmatrix} =\begin{bmatrix}\color{red}a\color{red}a+\color{red}b\color{red}b+\color{red}c\color{red}c& \color{red}a\color{blue}d+\color{red}b\color{blue}e+\color{red}c\color{blue}f \\ \color{blue}d\color{red}a+ \color{blue}e\color{red}b+\color{blue}f\color{red}c & \color{blue}d\color{blue}d+\color{blue}e\color{blue}e+\color{blue}f\color{blue}f\end{bmatrix}$$

  • 식 2와 같이 앞 행렬의 행과 뒤 행렬의 열 사이에서 연산이 이루어지므로 앞행렬의 열수과 뒤 행렬의 행 수가 일치해야 합니다.
  • 행렬곱의 결과의 차원은 앞행렬의 행수와 뒤 행렬의 열수가 됩니다.
    • ⇒ m$\times$n · n$\times$p = m$\times$p

예 2)

행렬 A, B의 행렬곱

$$A=\begin{bmatrix}2& 3\\ 1& -5 \end{bmatrix} \quad B=\begin{bmatrix} 4& 3& 6\\1& -2& 3\end{bmatrix}$$

A=np.mat("2,3; 1, -5")
B=np.mat("4,3,6; 1, -2, 3")
A.shape, B.shape
((2, 2), (2, 3))
AB=A.dot(B)
print(AB)
[[11  0 21]
 [-1 13 -9]]

행렬곱은 위 코드와 같이 np.dot(a, b) 함수 또는 메소드 a.dot(b)를 적용할 수 있습니다. 또한 연산자인 @을 사용할 수 있습니다.

print(A@B)
[[11  0 21]
 [-1 13 -9]]

행렬곱에서는 교환법칙이 성립되지 않습니다.

예 2)

행렬 A, B의 행렬곱의 교환법칙여부를 확인합니다.

$$A=\begin{bmatrix}5& 1\\ 3& -2 \end{bmatrix} \quad B=\begin{bmatrix} 2& 0\\ 4& 3\end{bmatrix}$$

A=np.mat("5,1; 3,-2")
B=np.mat("2,0; 4, 3")
AB=A@B
print(AB)
[[14  3]
 [-2 -6]]
BA=B@A
print(BA)
[[10  2]
 [29 -2]]
np.array_equal(AB, BA)
False

전치행렬의 특성은 식 2와 같습니다.

\begin{align}(A^T)^T=A\\ \tag{식 2}(A+B)^T=A^T+B^T\\(rA)^T=rA^T\\(AB)^T=B^TA^T\end{align}

예 2의 두 행렬 A, B에 대해 식 2를 확인해 봅니다.

A=np.mat("5,1; 3,-2")
B=np.mat("2,0; 4, 3")
ATT=A.T.T
np.array_equal(A, ATT)
True
np.array_equal((A+B).T, A.T+B.T)
True
np.array_equal((A@B).T, B.T@A.T)
True
np.array_equal((3*A).T, 3*(A.T))
True

댓글

이 블로그의 인기 게시물

[Linear Algebra] 유사변환(Similarity transformation)

유사변환(Similarity transformation) n×n 차원의 정방 행렬 A, B 그리고 가역 행렬 P 사이에 식 1의 관계가 성립하면 행렬 A와 B는 유사행렬(similarity matrix)이 되며 행렬 A를 가역행렬 P와 B로 분해하는 것을 유사 변환(similarity transformation) 이라고 합니다. $$\tag{1} A = PBP^{-1} \Leftrightarrow P^{-1}AP = B $$ 식 2는 식 1의 양변에 B의 고유값을 고려한 것입니다. \begin{align}\tag{식 2} B - \lambda I &= P^{-1}AP – \lambda P^{-1}P\\ &= P^{-1}(AP – \lambda P)\\ &= P^{-1}(A - \lambda I)P \end{align} 식 2의 행렬식은 식 3과 같이 정리됩니다. \begin{align} &\begin{aligned}\textsf{det}(B - \lambda I ) & = \textsf{det}(P^{-1}(AP – \lambda P))\\ &= \textsf{det}(P^{-1}) \textsf{det}((A – \lambda I)) \textsf{det}(P)\\ &= \textsf{det}(P^{-1}) \textsf{det}(P) \textsf{det}((A – \lambda I))\\ &= \textsf{det}(A – \lambda I)\end{aligned}\\ &\begin{aligned}\because \; \textsf{det}(P^{-1}) \textsf{det}(P) &= \textsf{det}(P^{-1}P)\\ &= \textsf{det}(I)\end{aligned}\end{align} 유사행렬의 특성 유사행렬인 두 정방행렬 A와 B는 'A ~ B' 와 같...

[sympy] Sympy객체의 표현을 위한 함수들

Sympy객체의 표현을 위한 함수들 General simplify(x): 식 x(sympy 객체)를 간단히 정리 합니다. import numpy as np from sympy import * x=symbols("x") a=sin(x)**2+cos(x)**2 a $\sin^{2}{\left(x \right)} + \cos^{2}{\left(x \right)}$ simplify(a) 1 simplify(b) $\frac{x^{3} + x^{2} - x - 1}{x^{2} + 2 x + 1}$ simplify(b) x - 1 c=gamma(x)/gamma(x-2) c $\frac{\Gamma\left(x\right)}{\Gamma\left(x - 2\right)}$ simplify(c) $\displaystyle \left(x - 2\right) \left(x - 1\right)$ 위의 예들 중 객체 c의 감마함수(gamma(x))는 확률분포 등 여러 부분에서 사용되는 표현식으로 다음과 같이 정의 됩니다. 감마함수는 음이 아닌 정수를 제외한 모든 수에서 정의됩니다. 식 1과 같이 자연수에서 감마함수는 factorial(!), 부동소수(양의 실수)인 경우 적분을 적용하여 계산합니다. $$\tag{식 1}\Gamma(n) =\begin{cases}(n-1)!& n:\text{자연수}\\\int^\infty_0x^{n-1}e^{-x}\,dx& n:\text{부동소수}\end{cases}$$ x=symbols('x') gamma(x).subs(x,4) $\displaystyle 6$ factorial 계산은 math.factorial() 함수를 사용할 수 있습니다. import math math.factorial(3) 6 a=gamma(x).subs(x,4.5) a.evalf(3) 11.6 simpilfy() 함수의 알고리즘은 식에서 공통사항을 찾아 정리하...

sympy.solvers로 방정식해 구하기

sympy.solvers로 방정식해 구하기 대수 방정식을 해를 계산하기 위해 다음 함수를 사용합니다. sympy.solvers.solve(f, *symbols, **flags) f=0, 즉 동차방정식에 대해 지정한 변수의 해를 계산 f : 식 또는 함수 symbols: 식의 해를 계산하기 위한 변수, 변수가 하나인 경우는 생략가능(자동으로 인식) flags: 계산 또는 결과의 방식을 지정하기 위한 인수들 dict=True: {x:3, y:1}같이 사전형식, 기본값 = False set=True :{(x,3),(y,1)}같이 집합형식, 기본값 = False ratioal=True : 실수를 유리수로 반환, 기본값 = False positive=True: 해들 중에 양수만을 반환, 기본값 = False 예 $x^2=1$의 해를 결정합니다. solve() 함수에 적용하기 위해서는 다음과 같이 식의 한쪽이 0이 되는 형태인 동차식으로 구성되어야 합니다. $$x^2-1=0$$ import numpy as np from sympy import * x = symbols('x') solve(x**2-1, x) [-1, 1] 위 식은 계산 과정은 다음과 같습니다. $$\begin{aligned}x^2-1=0 \rightarrow (x+1)(x-1)=0 \\ x=1 \; \text{or}\; -1\end{aligned}$$ 예 $x^4=1$의 해를 결정합니다. solve() 함수의 인수 set=True를 지정하였으므로 결과는 집합(set)형으로 반환됩니다. eq=x**4-1 solve(eq, set=True) ([x], {(-1,), (-I,), (1,), (I,)}) 위의 경우 I는 복소수입니다.즉 위 결과의 과정은 다음과 같습니다. $$x^4-1=(x^2+1)(x+1)(x-1)=0 \rightarrow x=\pm \sqrt{-1}, \; \pm 1=\pm i,\; \pm1$$ 실수...