Lecture 4 Matrices and Linear Algebra with Python
Lecture 4 Matrices and Linear Algebra with Python Dr. Qi Ying
Objectives • Review Matrix Operations • Review Linear Algebra – Linear systems of equations – Matrix operations • Solve linear systems of equations in Python
Matrix Notation Principle diagonal http: //en. wikipedia. org/wiki/Matrix_%28 mathematics%29
Matrix Notation • Row vector and column vector
Matrix Terminology • Diagonal matrix: square matrix where all elements off the main diagonal are zero • Identity matrix: diagonal matrix where all elements on the main diagonal are equal to 1
Matrix Terminology • Upper/lower triangular matrix
Matrix Terminology • Banded matrix Tridiagonal matrix: Band width = 3
Matrix Operation • Transpose: exchange rows for columns
Matrix Terminology • Symmetric matrix: aij=aji T or A =A
Matrix Operation • Addition/subtraction – Must be of the same size – Perform operation element by element
Matrix Operation • Multiplication with a scalar – The scalar is multiplied with each element to form a new matrix
Matrix Operation • Multiplication with matrix – Number of columns in the first matrix must equal to the number of rows in the second matrix row 1 Column 2
Matrix Operation • In general, matrix multiplication is NOT commutative: • For square matrix:
Matrix Operation • Matrix inversion: for square matrix B is defined as the inverse of matrix A, or [B]=[A]-1
Matrix Operation • Matrix inversion for 2 x 2 matrix
Linear systems of equations
Linear systems of equations • Solution of linear systems using python import numpy as np #define matrix a a=np. array([[5, 3, 2], [4, 3, 7], [7, 5, 1]]) print('matrix A=') print(a) # calculate the inverse matrix ainv=np. linalg. inv(a) print('inv(A)=') print(ainv) # define matrix b b=np. array([7, 9, 5]) b. shape=(3, 1) # use dot product for matrix*vector x=np. dot(ainv, b) # can also use matmul: x=np. matmul(ainv, b) print('x=inv(A)*b') print(x)
Linear systems of equations • Check the results: matrix A= [[5 3 2] [4 3 7] [7 5 1]] inv(A)= [[ 1. 18518519 -0. 25925926 -0. 55555556] [-1. 66666667 0. 3333 1. ] [ 0. 03703704 0. 14814815 -0. 1111]] [ 3. 18518519 -3. 66666667 1. 03703704] x=inv(A)*b [[ 3. 18518519] [-3. 66666667] [ 1. 03703704]]
Matrix Operation • Matrix augmentation: adding one or more columns to the original matrix. – Useful when we want to apply identical row operations on two matrices.
- Slides: 19