Son Tu

Từ Nguyễn Thái Sơn

Spring 2023


CMSE/MTH 314 Matrix Algebra with Computational Applications

Materials

All materials are hosted on D2L.

Table of contents

Some extra notes


Slicing arrays

We can use v[start:end:step] to slide an array. It can be used with python list, tuple or numpy.ndarray (vectors created by calling np.arrray([1,21,3]) for example). Read more at NumPy Array Slicing.

import numpy as np
v = np.array([1, 2, 3, 4, 5])

type(v)
>>> numpy.ndarray

v[0::] # select all indices, defaut step 1
>>> array([1, 2, 3, 4, 5])

v[0:-1:] # select all indices except the last one
>>> array([1, 2, 3, 4])

v[0:3:] # select only indices 0, 1, 2
>>> array([1, 2, 3])

v[0:3:2] # select only indices 0, 2 as the step is 2
>>> array([1, 3])

Numerical error

Avoid using the comparison 1==1.0 or generally a==b when comparing two scalars. Use np.isclose() instead.

import numpy as np
np.isclose(1, 1.0)
>>> True

Creating zeros and ones vectors

np.ones(4)
>>> array([1., 1., 1., 1.])

np.zeros(4)
>>> array([0., 0., 0., 0.])

np.zeros((2, 3))
>>> array([[0., 0., 0.],
   [0., 0., 0.]])

[[0 for i in range(n)] for j in range(m)]
>>> [[0, 0, 0], [0, 0, 0]]

Solving linear systems

import numpy as np
A = np.array([[1, 0, 1], [2, 3, 4], [-1, -3, -3]])
b = np.array([3, 7, -4])
sol = np.linalg.solve(A,b)

Note that one can use np.matrix instead of np.array, however the former is deprecated.

Find the reduced echelon form

The Python sympy library has a "reduced row echelon form" (rref) function that runs a much more efficient version of the Gauss-Jordan elimination. To use the rref function you must first convert your matrix into a sympy.Matrix and then run the function. For example, let's do this for the following matrix:

import sympy as sym
M = sym.Matrix([[1, 0, 1, 3], [2, 3, 4, 7], [-1, -3, -3, -4]])
M
M.rref()

In this code, the augmented matrix is \( M = [A|b]\) where

$$ A = \begin{pmatrix} 1 & 0 & 1 \\ 2 & 3 & 4 \\ -1 & -3 & -3 \end{pmatrix} , \qquad\text{and}\qquad b = \begin{pmatrix} 3\\ 7\\ -4 \end{pmatrix}. $$

Note that M.rref() returns a tuple of length 2, the first one is the reduced echelon form, the second one is the tuple if incides of pivots.

import sympy as sym
M = sym.Matrix([[1, 0, 1, 3], [2, 3, 4, 7], [-1, -3, -3, -4]])
M
M.rref()[0]

This code returns the matrix only, which we use mostly in this course.

Getting the dimensions of arrays/matrix

A = [[1,2,3],[4,5,6]]
len(A) # return 2
len(A[0]) # return 3

B = np.array([[1,2,3],[4,5,6]])
len(B) # return 2
len(B[0]) # return 3
B = np.array([[1,2,3],[4,5,6]])
len(B) # return 2
len(B[0]) # return 1 - wrong
# fix
len(np.array(B[0])) # return 3

© 2016-2024 Son N. T. Tu. Powered by Ark. Last updated: October 02, 2024.