Matrix¶
Module contents¶
- matrixflow.solve_linear_system(coefficients: Sequence[Sequence[int | float | Fraction]], b: Sequence[int | float | Fraction]) list[Fraction]¶
Solves a system of
nlinear equations withnvariables: \(\mathbf{A}x=\mathbf{b}\)It returns \(x\) by computing \(x=\mathbf{A}^{-1}\mathbf{b}\)
- Parameters:
- Returns:
An array of solutions with values corresponding to the respective unknowns
- Return type:
list[
Fraction]
Example
>>> solve_linear_system( [[2, 3], [5, -6]], [4, -4] ) [Fraction(4, 9), Fraction(28, 27)]
This is equivalent to:
\(\begin{cases}2x+3y=4\\5x-6y=-4\end{cases}\)
\(\therefore x=\frac{4}{9}, y=\frac{28}{27}\)
- class matrixflow.Matrix(entries: Sequence[Sequence[int | float | Fraction]])¶
An implementation for a 2D mathematical matrix
- Parameters:
entries (Sequence[Sequence[int | float | Fraction]]) – The raw entries to initialize the matrix with
- Raises:
IndexError – Entries have rows with inconsistent sizes
- classmethod from_row_vector(row: Vector) Self¶
Typecasts a row vector to an equivalent matrix with a single row
- classmethod from_col_vector(col: Vector) Self¶
Typecasts a column vector to an equivalent matrix with a single row
- classmethod from_1D(entries: Sequence[int | float | Fraction], cols: int) Self¶
Creates a matrix with
colsnumber of columns from a flat, 1D sequence
- classmethod from_columns(columns: Sequence[Sequence[int | float | Fraction]]) Self¶
Creates a new matrix from a list of
columnsof the matrixThis is useful for creating transformations where
columnsdirectly corresponds to the list of respective transformed basis vectors
- classmethod zero(rows: int, cols: int) Self¶
Creates a
rowsxcolssized matrix \(\mathbf{0}\) all filled with0\(\mathbf{A0}=\mathbf{0}\) for all matrices \(\mathbf{A}\)
- classmethod identity(n: int) Self¶
Creates the identity matrix \(\mathbf{I}\) of size
nA square matrix filled with0except for1on its major diagonal\(\mathbf{AI}=\mathbf{IA}=\mathbf{A}\) for all matrices \(\mathbf{A}\)
- classmethod shear_2d(x_gradient: int | float | Fraction = 0, y_gradient: int | float | Fraction = 0) Self¶
Creates a linear map that performs a shear
A shear displaces each point in a fixed direction by an fixed amount relative to a fixed line (i.e. the axes)
- classmethod reflect_x() Self¶
Creates a linear map that performs a vertical reflection across the horizontal (x-axis)
- Returns:
The created linear map
- Return type:
- classmethod reflect_y() Self¶
Creates a linear map that performs a horizontal reflection across the vertical (y-axis)
- Returns:
The created linear map
- Return type:
- classmethod squeeze_map_2d(r: int | float | Fraction = 1) Self¶
Creates a linear map that performs a squeeze map
A squeeze map is a transformation that preserves euclidean area of regions in the cartesian plane, but is not a rotation or shear
- classmethod scale_2d(k: int | float | Fraction = 1) Self¶
Creates a linear map that performs a uniform scale
A uniform scale enlarges or shrinks the regions in the cartesian plane by the same factor in all directions
- classmethod rotate_2d(theta: int | float | Fraction = 0) Self¶
Creates a linear map that performs a rotation
- property inner: list[list[Fraction]]¶
Returns a reference to the internal list representation of this matrix
- rot90() None¶
Rotates the entries of this matrix in place, in the positive angular direction (counter-clockwise) by 90 degrees
- Return type:
None
- transpose() None¶
Transposes this matrix \(\mathbf{A}\) in place: switches the
rowswith thecolumns\(\mathbf{A}\mapsto\mathbf{A}^\intercal\)
- Return type:
None
- transposed() Matrix¶
Computes a new matrix that is this matrix \(\mathbf{A}\)’s transpose: switches the
rowswith thecolumns- Returns:
The transposed matrix: \(\mathbf{A}^\intercal\)
- Return type:
- add_row(row: Sequence[int | float | Fraction]) None¶
Appends a row
rowonto the end of this matrix- Parameters:
row (Sequence[int | float | Fraction]) – The row to append onto this matrix
- Raises:
IndexError – The size of the new row does not match the existing matrix’s row size
- Return type:
None
- add_col(col: Sequence[int | float | Fraction]) None¶
Appends a column
colonto the end of this matrix- Parameters:
col (Sequence[int | float | Fraction]) – The column to append onto this matrix
- Raises:
IndexError – The size of the new column does not match the existing matrix’s column size
- Return type:
None
- is_square() bool¶
Returns
Trueif this matrix is square, elseFalse- Returns:
whether or not this matrix is square
- Return type:
- is_same_order(other: Matrix) bool¶
Returns
Trueif this matrix is of the same order asother, elseFalse
- is_singular() bool¶
Returns
Trueif this matrix \(\mathbf{A}\) is square and is singular: meaning \(\mathbf{A}^{-1}\) does not exist, elseFalse- Returns:
Whether or not this matrix is square and is singular
- Return type:
- is_symmetric() bool¶
Returns
Trueif this matrix \(\mathbf{A}\) is symmetric: \(\mathbf{A}=\mathbf{A}^\intercal\), elseFalse- Returns:
Whether or not this matrix is symmetric
- Return type:
- is_skew_symmetric() bool¶
Returns
Trueif this matrix \(\mathbf{A}\) is skew-symmetric: \(\mathbf{A}=-\mathbf{A}^\intercal\), elseFalse- Returns:
Whether or not this matrix is skew-symmetric
- Return type:
- is_orthogonal() bool¶
Returns
Trueif this matrix \(\mathbf{A}\) is orthogonal: \(\mathbf{A}^\intercal=\mathbf{A}^{-1}\), elseFalse- Returns:
Whether or not this matrix is orthogonal
- Return type:
- is_upper_triangular() bool¶
Returns
Trueif this matrix is upper-triangular: meaning all elements below the main diagonal are zero.- Returns:
Whether or not this matrix is upper-triangular
- Return type:
- is_lower_triangular() bool¶
Returns
Trueif this matrix is lower-triangular: meaning all elements above the main diagonal are zero.- Returns:
Whether or not this matrix is lower-triangular
- Return type:
- is_diagonal() bool¶
Returns
Trueif this matrix is lower-triangular: meaning all elements that are not on the main diagonal are zero.- Returns:
Whether or not this matrix is diagonal
- Return type:
- row_add(i: int, j: int, k: int | float | Fraction) None¶
Elementary row operation 1: replaces row
iwith the sum of itself andktimes rowj:\(R_i+kR_j\rightarrow R_i\) where \(i\ne j\)
- row_mul(i: int, k: int | float | Fraction) None¶
Elementary row operation 2: multiplies each element in row
ibyk\(kR_i\rightarrow R_i\) where \(k\ne 0\)
- row_switch(i: int, j: int) None¶
Elementary row operation 3: switches row
iwith rowj\(R_i\leftrightarrow R_j\)
- row_echelon_form(b: None = None) tuple[Matrix, None]¶
- row_echelon_form(b: Matrix | Vector) tuple[Matrix, Matrix]
Computes a new matrix that is this matrix \(\mathbf{A}\)’s row echelon form using the Gaussian elimination algorithm
As a way to replicate augmented matrices of the form \(\mathbf{A}|\mathbf{B}\):
brepresents the right side of the augmented matrix \(\mathbf{B},\) while this matrix represents the left side \(\mathbf{A}\)bwill have the same row operations that were applied onto this matrix \(\mathbf{A}\), applied on itThe resulting row echelon form of \(\mathbf{A}\) must satisfy the following criteria:
The first nonzero entry in each row is a 1 (called a leading 1).
Each leading 1 comes in a column to the right of the leading 1s in rows above it. (this is the pivot point)
All rows that are all 0s come at the bottom of the matrix.
- reduced_row_echelon_form(b: None = None) tuple[Matrix, None]¶
- reduced_row_echelon_form(b: Matrix | Vector) tuple[Matrix, Matrix]
Computes a new matrix that is this matrix \(\mathbf{A}\)’s reduced row echelon form
Similar to
row_echelon_form():bwill mirror the row operations applied onto this matrix.It first computes the row echelon form \(\mathrm{rref}(\mathbf{A})\) using
row_echelon_form()that it will further reduce using the backwards steps of Gaussian EliminationThe resulting reduced row echelon form of \(\mathbf{A}\) must satisfy the following criteria:
It is in row echelon form
Each column that contains a leading 1 has 0s in all of its other entries
If \(\mathbf{A}\) is invertible (non-singular) then \(\mathrm{rref}(\mathbf{A})=\mathbf{I}\) and
b\(\mathbf{B}\) will represent the corresponding values of the solution to the linear system of equations represented by the augmented matrix \(\mathbf{A}|\mathbf{B}\).Additionally, computing \(\mathrm{rref}(\mathbf{A}|\mathbf{I})\) where
bis \(\mathbf{I}\) gives you \(\mathbf{I}|\mathbf{A}^{-1}\) providing that \(\mathbf{A}\) is invertible.
- change_basis(new_bases: Matrix) Matrix¶
Changes the bases of this linear transformation \(\mathbf{M}\),
into the new bases defined by
new_bases\(\mathbf{P}\), by computing: \(\mathbf{P}^{-1}\mathbf{M}\mathbf{P}\)
- get_submatrix_of(rows: set[int], cols: set[int]) Matrix¶
A submatrix is the matrix obtained by deleting the rows that that have indices in the set
rowsand columns that have indices in the setcols
- get_minor_at(i: int, j: int) Fraction¶
Computes the minor \(\mathbf{M}_{ij}\) of this matrix at \(\mathbf{A}_{ij}\)
The minor is the determinant of the submatrix after deleting row
iand columnj\(\mathbf{M}_{ij}=\det\left(\left(\mathbf{A}_{pq}\right)_{p\ne i,q\ne j}\right)\)
- Returns:
The minor: \(\mathbf{M}_{ij}\)
- Return type:
- Raises:
AssertionError – This matrix is not square
- Parameters:
- get_cofactor_at(i: int, j: int) Fraction¶
Computes the cofactor \(\mathbf{C}_{ij}\) of this matrix at \(\mathbf{A}_{ij}\)
The cofactor is simply the element’s signed minor: \(\mathbf{C}_{ij}=(-1)^{i+j}\cdot\mathbf{M}_{ij}\)
- Returns:
The cofactor: \(\mathbf{M}_{ij}\)
- Return type:
- Raises:
AssertionError – This matrix is not square
- Parameters:
- get_cofactor_matrix() Matrix¶
Computes the matrix of cofactors \(\mathbf{C}\) of this matrix
\(\mathbf{C}=\left((-1)^{i+j}\cdot\mathbf{M}_{ij}\right)_{0\le i,j\lt n}\)
- Returns:
The cofactor matrix
- Return type:
- Raises:
AssertionError – This matrix is not square
- adj() Matrix¶
Computes a new matrix that is this matrix \(\mathbf{A}\)’s adjugate matrix
\(\mathrm{adj}(\mathbf{A})=\mathbf{C}^\intercal\) where \(\mathbf{C}\) is the cofactor matrix
- Returns:
The adjugate matrix of this matrix
- Return type:
- Raises:
AssertionError – This matrix is not square
- det() Fraction¶
Computes the determinant of this matrix \(\mathbf{A}\)
The determinant of a matrix is the sum of all the products of the cofactor and element in any given row or column
\(|\mathbf{A}|=\det(\mathbf{A})=\displaystyle\sum_i{\mathbf{A}_{ij}\mathbf{C}_{ij}}=\displaystyle\sum_j{\mathbf{A}_{ij}\mathbf{C}_{ij}}\) where \(\mathbf{C}_{ij}\) is cofactor of \(\mathbf{A}_{ij}\)
The determinant of a matrix represents the scale factor of space it is applied on.
If \(\det(\mathbf{A})<0\), that means that a change of orientation has occured
If \(\det(\mathbf{A})=0\), that means that space has been squished down to a lower dimension than what it originally was: due to the fact that this transformation’s basis vectors are not all linearly independent thereby making this matrix singular.
If \(\mathbf{A}\) is upper-triangular or lower-triangular then \(\det(\mathbf{A})=\mathrm{tr}(\mathbf{A})\).
- Returns:
The determinant of the matrix: \(\det(\mathbf{A})\)
- Return type:
- Raises:
AssertionError – This matrix is not square
- trace() Fraction¶
Computes the trace of this square matrix \(\mathbf{A}\)
\(\mathrm{tr}(\mathbf{A})=\displaystyle\sum_i{\mathbf{A}_{ii}}\)
- Returns:
The trace of the square matrix: \(\mathrm{tr}(\mathbf{A})\)
- Return type:
- Raises:
AssertionError – This matrix is not square
- rank() int¶
Computes the rank of this matrix \(\mathbf{A}\) as a linear transformation
The rank of this matrix \(\rho(\mathbf{A})\) represents the number of linearly independent vectors (columns) of this linear transformation. It represents the dimensionality of space after the transformation
It can be computed as the number of non-zero rows in the row echelon form of this matrix
- Returns:
The rank of this matrix: \(\rho(\mathbf{A})\)
- Return type:
- inverted() Matrix¶
Computes a new matrix \(\mathbf{A}^{-1}\) that is this matrix \(\mathbf{A}\)’s inverse
\(\mathbf{A}^{-1}=\frac{\mathrm{adj}\left(\mathbf{A}\right)}{\det(\mathbf{A})}\) if \(\det(\mathbf{A})\ne0\) where \(\mathbf{A}^{-1}\mathbf{A}=\mathbf{A}\mathbf{A}^{-1}=\mathbf{I}\)
(\(\mathbf{A}^{-1}\) is the transformation that undos this transformation \(\mathbf{A}\))
- Returns:
The new new inverse matrix: \(\mathbf{A}^{-1}\)
- Return type:
- Raises:
ValueError – This matrix singular: \(\det(\mathbf{A})=0\) (inverse does not exist)
AssertionError – This matrix is not square
- invert() None¶
Inverts this matrix in place
\(\mathbf{A}\mapsto\mathbf{A}^{-1}\) if \(\det(\mathbf{A})\ne0\) where \(\mathbf{A}^{-1}\mathbf{A}=\mathbf{A}\mathbf{A}^{-1}=\mathbf{I}\)
- Returns:
The inverted matrix: \(\mathbf{A}^{-1}\)
- Return type:
- Raises:
ValueError – This matrix singular: \(\det(\mathbf{A})=0\) (inverse does not exist)
AssertionError – This matrix is not square
- copy() Self¶
Makes a deepcopy of this matrix and its elements
- Returns:
The copied matrix
- Return type:
- display() str¶
Returns a formatted, displayable string representation of this matrix
- Returns:
The formatted string
- Return type:
- __add__(other: Matrix) Self¶
Computes a new matrix that is the sum of this matrix \(\mathbf{A}\) and
other\(\mathbf{B}\)- Parameters:
other (Matrix) – The matrix to perform the addition with
- Returns:
The sum matrix: \(\mathbf{A}+\mathbf{B}\)
- Return type:
- Raises:
AssertionError – Attempted to add matrices of different orders
- __iadd__(other: Matrix) Self¶
Adds
other\(\mathbf{B}\) onto this matrix \(\mathbf{A}\) (in place)- Parameters:
other (Matrix) – The matrix to perform the addition with
- Returns:
The sum matrix: \(\mathbf{A}+\mathbf{B}\)
- Return type:
- Raises:
AssertionError – Attempted to add matrices of different orders
- __sub__(other: Matrix) Self¶
Computes a new matrix that is the difference of this matrix \(\mathbf{A}\) and
other\(\mathbf{B}\)- Parameters:
other (Matrix) – The matrix to perform the subtraction with
- Returns:
The difference matrix: \(\mathbf{A}-\mathbf{B}\)
- Return type:
- Raises:
AssertionError – Attempted to subtract matrices of different orders
- __isub__(other: Matrix) Self¶
Subtracts
other\(\mathbf{B}\) from this matrix \(\mathbf{A}\) (in place)- Parameters:
other (Matrix) – The matrix to perform the subtraction with
- Returns:
The difference matrix: \(\mathbf{A}-\mathbf{B}\)
- Return type:
- Raises:
AssertionError – Attempted to subtract matrices of different orders
- __rmul__(other: int | float | Fraction) Self¶
Computes a new matrix that is the scalar multiplication of
other\(k\) on this matrix \(\mathbf{A}\)
- __mul__(other: int | float | Fraction) Self¶
Computes a new matrix that is the scalar multiplication of
other\(k\) on this matrix \(\mathbf{A}\)
- __imul__(other: int | float | Fraction) Self¶
Scalar multiplies
other\(k\) on this matrix \(\mathbf{A}\) (in place)
- __truediv__(other: int | float | Fraction) Self¶
Computes a new matrix that is the scalar division of
other\(k\) on this matrix \(\mathbf{A}\)
- __itruediv__(other: int | float | Fraction) Self¶
Scalar divides
other\(k\) on this matrix \(\mathbf{A}\) (in place)
- __floordiv__(other: int | float | Fraction) Self¶
Computes a new matrix that is the result of scalar floor division of
other\(k\) on this matrix \(\mathbf{A}\)
- __ifloordiv__(other: int | float | Fraction) Self¶
Scalar floor divides
other\(k\) on this matrix \(\mathbf{A}\) (in place)
- __matmul__(other: Matrix) Matrix¶
- __matmul__(other: Vector) Vector
Overloaded method:
Computes a new matrix that is the matrix multiplication between this matrix \(\mathbf{A}\) (size \(m\times n\)) and
other\(\mathbf{B}\) (size \(p\times q\))The operation can only be performed if \(n = p\) and will yield a matrix of size \(m\times q\)
\(\mathbf{AB}=\left(\displaystyle\sum_r{\mathbf{A}_{ir}\mathbf{B}_{ij}}\right)_{1\le i,j\lt n}\)
This can also represent a composition of 2 linear maps: \(f\circ g=f(g(\vec{v}))\) which says: apply \(g\) first, then \(f\), where this matrix represents the map \(f\) and
otherrepresents the map \(g\)Applies the linear transformation that is this matrix \(\mathbf{A}\) on the vector
other\(\vec{v}\):The operation can only be performed if \(n = \ell(\vec{v})\) where \(\ell(\vec{v})\) denotes the length of the vector
\(\mathrm{T_A}(\vec{v})=\mathbf{A}\vec{v}\) yielding a new output vector that is the transformed vector
- Parameters:
other (Matrix | Vector) – The matrix / vector to perform matrix multiplication with
- Returns:
The matrix / vector that is the result of the matrix multiplication
- Return type:
- Raises:
AssertionError – Unable to compute matrix multiplication: The # of columns in the left matrix does not match the # of rows in the right matrix / vector
- __pow__(other: int) Matrix¶
Computes repeated matrix multiplication of this matrix \(\mathbf{A}\) on itself
othernumber of times- Parameters:
other (int) – The exponent: \(n\)
- Returns:
The new matrix that is this matrix raised to the power of
other: \(\mathbf{A}^n\)- Return type:
- Raises:
AssertionError – Unable to compute matrix multiplication: The # of columns in the left matrix does not match the # of rows in the right matrix
- __pos__() Self¶
Unary plus: does nothing as it performs a scalar multiplication of all the elements by \(+1\)
- Returns:
Returns itself
- Return type:
- __neg__() Self¶
Negates this matrix \(\mathbf{A}\) (negates all of its elements)
- Returns:
Returns the negated vector: \({-\mathbf{A}}\)
- Return type:
- __len__() int¶
Returns the number of rows in this matrix:
self.rows- Returns:
The number of rows in this matrix
- Return type:
- __abs__() Fraction¶
Computes the determinant of this matrix:
See:
det()- Returns:
The determinant of this matrix
- Return type:
- Raises:
AssertionError – This matrix is not square
- __invert__() Matrix¶
Computes a new matrix that is this matrix’s inverse
See:
inverted()- Returns:
The new new inverse matrix: \(\mathbf{A}^{-1}\)
- Return type:
- Raises:
ValueError – This matrix singular: \(\det(\mathbf{A})=0\) (inverse does not exist)
- __contains__(target: int | float | Fraction) bool¶
Returns
Trueif the valuetargetcan be found in this matrix, elseFalse
- __copy__() Self¶
Creates a copy of this matrix and its elements
- Returns:
The copied matrix
- Return type: