symbolic
ma1522.symbolic.Matrix(*args, aug_pos: Iterable[int] | int | None = None, **kwargs)
¶
Bases: MutableDenseMatrix
A symbolic matrix class extending MutableDenseMatrix with enhanced linear algebra operations.
The inherited methods from MutableDenseMatrix
can be found in the SymPy Matrices Documentation. A summary of the
inherited attributes and methods is also available on the Inherited Methods Summary page.
This class provides comprehensive linear algebra functionality with support for
- Matrix creation from various sources (lists, \(\rm\LaTeX\), random values)
- Matrix decompositions (REF, RREF, LU, QR, SVD, diagonalization)
- Vector space operations (orthogonalization, projections, basis manipulation)
- Eigenvalue/eigenvector computations
- Custom printing and \(\rm\LaTeX\) formatting with augmented matrix support
Key Features
- Maintains symbolic expressions throughout operations
- Follows MA1522 syllabus conventions for linear algebra
- Provides detailed step-by-step output for learning purposes
- Supports both exact symbolic and numerical computations
Attributes:
-
_aug_pos(set[int]) –Set of column indices where augmentation lines should be drawn for displaying augmented matrices.
Examples:
Basic matrix operations:
| Python Console Session | |
|---|---|
Creating from LaTeX:
| Python Console Session | |
|---|---|
Eigenvalue decomposition:
| Python Console Session | |
|---|---|
Methods:
-
from_latex–Converts a \(\rm\LaTeX\) matrix/vector expression into a Matrix object.
-
from_str–Parses a string representation of a matrix into a Matrix.
-
from_list–Creates a Matrix object from a list of vectors.
-
create_unk_matrix–Creates a symbolic matrix with unknown entries.
-
create_rand_matrix–Creates a matrix with random entries.
-
copy–Creates a copy of the matrix, preserving augmentation lines.
-
subs–Substitutes values in the matrix entries.
-
simplify–Simplifies the matrix by applying various simplification techniques.
-
identify–Identifies the matrix by applying a transformation function to each entry.
-
select_cols–Selects columns from the matrix based on the provided column indices.
-
select_rows–Selects rows from the matrix based on the provided row indices.
-
sep_part_gen–Separates a matrix into its particular and general solution parts.
-
sep_unk–Separates the matrix into matrices with each free symbol set to 1.
-
scalar_factor–Factorizes a matrix into the form \(\mathbf{A} = \mathbf{FD}\), where \(\mathbf{D}\) is a diagonal matrix
-
aug_line–Inserts an augmented line at the specified position.
-
rm_aug_line–Remove an augmentation line from the matrix.
-
row_join–Joins two matrices horizontally (column-wise), preserving augmentation lines.
-
col_join–Joins two matrices vertically (row-wise), preserving augmentation lines.
-
scale_row–Scales a row of the matrix by a scalar and simplifies the result.
-
swap_row–Swaps two rows of the matrix.
-
reduce_row–Reduces a row by subtracting a scalar multiple of another row.
-
get_pivot_row–Finds the row index of the pivot element in a given column.
-
get_pivot_pos–Finds the positions of the pivot elements in the matrix.
-
get_pivot_elements–Retrieves the pivot elements from the matrix.
-
ref–Find the Row Echelon Form (REF) of the matrix.
-
evaluate_cases–Evaluates and displays all possible cases for solutions to a linear system involving the matrix.
-
rref–Computes the Reduced Row Echelon Form (RREF) of the matrix.
-
rref_cases–Compute all symbolic-RREF cases by splitting on zero-pivot conditions.
-
solve–Solves the linear system
Ax = rhsforx. -
inverse–Computes the left or right inverse of a matrix, depending on its rank and the specified option.
-
elem–Returns the identity matrix with the same number of rows as the current matrix.
-
adjoint–Computes the adjugate (classical adjoint) of the matrix.
-
adj–Alias for the
adjointmethod. -
cramer_solve–Solves the linear system using Cramer's Rule.
-
column_constraints–Computes the column constraints for the matrix by appending a symbolic vector.
-
normalized–Normalizes the column vectors of the matrix (scaling each vector to have a unit norm).
-
is_linearly_independent–Determines if the vectors in the matrix are linearly independent.
-
get_linearly_independent_vectors–Returns a matrix containing the linearly independent vectors from the column space or row space.
-
simplify_basis–Returns a simplified basis for the column space or row space of the matrix.
-
extend_basis–Extends the matrix to form a basis for the span of the given subspace.
-
intersect_subspace–Computes the intersection of two subspaces by finding the nullspace of their orthogonal complements.
-
is_subspace_of–Checks if the current matrix is a subspace of another matrix.
-
is_same_subspace–Checks if two subspaces are the same by verifying if each subspace is a subspace of the other.
-
coords_relative–Computes the coordinates of the current vector relative to a given basis.
-
transition_matrix–Computes the transition matrix that transforms this matrix to another matrix.
-
nullspace–Computes the null space (kernel) of the matrix, i.e., the set of vectors that satisfy
self @ x = 0. -
nullity–Computes the nullity of the matrix, which is the dimension of its null space.
-
orthogonal_complement–Computes the orthogonal complement of the matrix (the null space of its transpose).
-
is_vec_orthogonal–Checks if the column vectors of the matrix are orthogonal to each other.
-
is_mat_orthogonal–Checks if the matrix is orthogonal (i.e., its columns are orthonormal).
-
orthogonal_decomposition–Decomposes the current vector (or matrix) into its orthogonal projection onto a subspace and its orthogonal complement.
-
proj_comp–Computes the orthogonal projection of the current vector (or matrix) onto the subspace spanned by the columns of another matrix.
-
norm_comp–Computes the component of the current vector (or matrix) orthogonal to the subspace spanned by the columns of another matrix.
-
gram_schmidt–Performs Gram-Schmidt orthogonalization to convert a set of vectors (columns of the matrix) into
-
QRdecomposition–Computes the QR decomposition of the matrix. Optionally computes the full QR decomposition.
-
solve_least_squares–Solves the least squares problem \(\min || \mathrm{self} \, \mathbf{x} - \mathrm{rhs}||^2\).
-
create_vander–Creates a Vandermonde matrix with symbolic entries.
-
apply_vander–Applies a Vandermonde transformation to the current matrix using the given vector.
-
cpoly–Computes the characteristic polynomial of the matrix and attempts to factor it into real and complex parts.
-
is_diagonalizable–Checks if the matrix is diagonalizable, with the option to focus only on real eigenvalues.
-
eigenvects_associated–Computes the eigenvectors associated with a given eigenvalue.
-
diagonalize–Diagonalizes the matrix if possible, focusing on real eigenvalues unless specified otherwise.
-
is_orthogonally_diagonalizable–Determines whether the matrix is orthogonally diagonalizable.
-
orthogonally_diagonalize–Orthogonally diagonalizes the matrix, ensuring that eigenvectors corresponding to different eigenvalues are orthogonal.
-
is_stochastic–Checks if the matrix is stochastic.
-
equilibrium_vectors–Computes the equilibrium vectors of the matrix, i.e., the nullspace of (I - A).
-
singular_value_decomposition–Performs Singular Value Decomposition (SVD) on the matrix, following the MA1522 syllabus.
-
fast_svd–A faster version of SVD that computes numerically using NumPy's SVD function.
-
standard_matrix–Returns the standard matrix for the transformation from self to out.
Source code in src/ma1522/symbolic.py
from_latex(expr: str, verbosity: int = 1, row_join: bool = True, norm: bool = False, aug_pos: Iterable[int] | int | None = None) -> Matrix
staticmethod
¶
Converts a \(\rm\LaTeX\) matrix/vector expression into a Matrix object.
Parses \(\rm\LaTeX\) matrix environments (pmatrix, array) and vector lists into a Matrix. Handles matrix multiplication expressions and normalizes vectors when requested.
Parameters:
-
expr(str) –\(\rm\LaTeX\) string containing:
- Matrix environments:
\begin{pmatrix} ... \end{pmatrix},\begin{array}{ccc} ... \end{array} - Vector lists:
\{ \begin{pmatrix} ... \end{pmatrix}, \begin{pmatrix} ... \end{pmatrix}\} - Matrix products:
\begin{pmatrix}...\end{pmatrix}\begin{pmatrix} ... \end{pmatrix}
- Matrix environments:
-
verbosity(int, default:1) –Controls output detail level: - 0: No output - 1: Display parsed matrix
-
row_join(bool, default:True) –If True, vector lists are treated as columns. If False, vectors are treated as rows.
-
norm(bool, default:False) –If True, normalizes vectors to unit length.
-
aug_pos(Iterable[int] | int | None, default:None) –If provided, specifies the column indices where augmentation lines should be drawn in the output matrix. This is useful for displaying augmented matrices in a visually clear manner. If
None, no augmentation lines are drawn.
Returns:
-
Matrix–The parsed matrix with optional normalization.
Raises:
-
Exception–If the \(\rm\LaTeX\) expression is empty, invalid or cannot be parsed.
Examples:
| Python Console Session | |
|---|---|
| Python Console Session | |
|---|---|
Source code in src/ma1522/symbolic.py
| Python | |
|---|---|
189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 | |
from_str(matrix_str: str, row_sep: str = ';', col_sep: str = ' ', aug_pos: Iterable[int] | int | None = None, is_real: bool = True) -> Matrix
staticmethod
¶
Parses a string representation of a matrix into a Matrix.
This method enables quick creation of a Matrix object from a string format similar to
the one used in MATLAB. It supports both row and column separators and
uses SymPy's parse_expr to convert
the entries of the matrix from a string format into a Matrix object.
Parameters:
-
matrix_str(str) –The string representation of the matrix.
-
row_sep(str, default:';') –The separator for rows in the string.
-
col_sep(str, default:' ') –The separator for columns in the string.
-
aug_pos(Iterable[int] | int | None, default:None) –If provided, specifies the column indices where augmentation lines should be drawn in the output matrix. This is useful for displaying augmented matrices in a visually clear manner. If
None, no augmentation lines are drawn. -
is_real(bool, default:True) –If True, the symbols in the matrix are considered real-valued. Otherwise, they are complex.
Returns:
-
Matrix–A Matrix object representing the parsed matrix.
Raises:
-
SyntaxError–If the string cannot be parsed into a matrix.
Examples:
Source code in src/ma1522/symbolic.py
from_list(vectors: list[Matrix], row_join: bool = True, aug_pos: Iterable[int] | int | None = None) -> Matrix
staticmethod
¶
Creates a Matrix object from a list of vectors.
This method takes a list of vectors (each represented as a Matrix object) and combines them into a single matrix.
Parameters:
-
vectors(list[Matrix]) –A list of Matrix objects, where each Matrix represents a row or column vector.
-
row_join(bool, default:True) –If True, the vectors are joined horizontally. If False, the vectors are stacked vertically.
-
aug_pos(Iterable[int] | int | None, default:None) –If provided, specifies the column indices where augmentation lines should be drawn in the output matrix. This is useful for displaying augmented matrices in a visually clear manner. If
None, no augmentation lines are drawn.
Returns:
-
Matrix–A matrix constructed from the list of vectors.
Raises:
-
ShapeError–If the vectors do not have compatible dimensions for joining.
Examples:
| Python Console Session | |
|---|---|
| Python Console Session | |
|---|---|
Source code in src/ma1522/symbolic.py
create_unk_matrix(r: int = 1, c: int = 1, symbol: str | None = None, is_real: bool | None = True, shape: Shape | None = None) -> Matrix
staticmethod
¶
Creates a symbolic matrix with unknown entries.
This method generates a matrix of size \(r \times c\) with symbolic
entries. The entries are named based on the provided symbol parameter and
indexed by their row and column positions. The is_real flag determines whether
the symbols are real-valued.
Note
- For a column vector without a specified symbol, the entries will be named following conventions, i.e., \(\begin{pmatrix} x \end{pmatrix}\), \(\begin{pmatrix} x \\ y \end{pmatrix}\), \(\begin{pmatrix} x \\ y \\ z \end{pmatrix}\), for 1, 2 and 3 rows respectively.
Parameters:
-
r(int, default:1) –The number of rows in the matrix.
-
c(int, default:1) –The number of columns in the matrix.
-
symbol(str, default:None) –The base name for the symbols used in the matrix entries.
-
is_real(bool, default:True) –If True, the symbols are real-valued. Otherwise, they are complex.
-
shape(Shape, default:None) –If provided, the matrix will be reshaped to this specific shape. Supported shapes include:
- DIAGONAL: Returns a diagonal matrix.
- SCALAR: Returns a scalar matrix.
- UPPER: Returns an upper triangular matrix.
- LOWER: Returns a lower triangular matrix.
- STRICT_UPPER: Returns an upper triangular matrix without the diagonal.
- STRICT_LOWER: Returns a lower triangular matrix without the diagonal.
- SYMMETRIC: Returns a symmetric matrix.
Returns:
-
Matrix–A matrix with symbolic entries of the specified size.
Raises:
-
NonSquareMatrixError–If
shapeis ill-defined on a non-square matrix.
Examples:
| Python Console Session | |
|---|---|
| Python Console Session | |
|---|---|
See Also
create_rand_matrix: Creates a matrix with random entries.
Source code in src/ma1522/symbolic.py
| Python | |
|---|---|
434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 | |
create_rand_matrix(r: int = 1, c: int = 1, shape: Shape | None = None, *args, **kwargs) -> Matrix
staticmethod
¶
Creates a matrix with random entries.
This method generates a matrix of size \(r \times c\) where the
entries are real integers. The values in the matrix are generated using SymPy's
randMatrix function.
Note
- The entries in the matrix are generated randomly and will change each time
the function is called. Setting a random seed using
seedin**kwargswill ensure reproducibility of the random values.
Parameters:
-
r(int, default:1) –The number of rows in the matrix.
-
c(int, default:1) –The number of columns in the matrix.
-
shape(Shape, default:None) –If provided, the matrix will be reshaped to this specific shape. Supported shapes include:
- DIAGONAL: Returns a diagonal matrix.
- SCALAR: Returns a scalar matrix.
- UPPER: Returns an upper triangular matrix.
- LOWER: Returns a lower triangular matrix.
- STRICT_UPPER: Returns an upper triangular matrix without the diagonal.
- STRICT_LOWER: Returns a lower triangular matrix without the diagonal.
- SYMMETRIC: Returns a symmetric matrix.
-
*args–Additional arguments passed to the
randMatrixfunction. -
**kwargs–Additional arguments passed to the
randMatrixfunction.
Returns:
-
Matrix–A Matrix with random entries of the specified size.
Raises:
-
NonSquareMatrixError–If
shapeis ill-defined on a non-square matrix.
Examples:
| Python Console Session | |
|---|---|
See Also
create_unk_matrix: Creates a matrix with symbolic entries.randMatrix: SymPy function to create a random matrix.
Source code in src/ma1522/symbolic.py
copy() -> Matrix
¶
Creates a copy of the matrix, preserving augmentation lines.
This method returns a new Matrix object that is a deep copy of the current matrix,
including any augmentation line positions (used for displaying augmented matrices).
Returns:
-
Matrix–A new matrix object with the same entries and augmentation lines as the original.
Examples:
| Python Console Session | |
|---|---|
Source code in src/ma1522/symbolic.py
subs(*args, **kwargs) -> Matrix
¶
Substitutes values in the matrix entries.
This method overrides SymPy's subs
method to ensure that the augmentation lines are preserved after substitution.
Parameters:
-
*args–Positional arguments for substitution.
-
**kwargs–Keyword arguments for substitution.
Returns:
-
Matrix–A new matrix with substituted values, preserving augmentation lines.
Examples:
| Python Console Session | |
|---|---|
Source code in src/ma1522/symbolic.py
simplify(rational: bool = True, suppress_warnings: bool = False, tolerance: float = 0.0001, simplify: bool = True, expand: bool = True, collect_sym: Symbol | None = None, *args, **kwargs) -> None
¶
Simplifies the matrix by applying various simplification techniques.
This method performs several operations on the matrix to simplify its entries
- Rational simplification.
- General symbolic simplification.
- Expansion or factoring of expressions.
- Collecting terms involving a specific symbol (if provided).
Note
- Rational simplification attempts to convert entries into rational numbers if possible. If there is a residue (e.g. attempting to convert a non-rational number into a rational), a warning is printed with the approximation error.
- Expansion and factoring can be controlled by the
expandparameter. - The matrix is modified in place.
Parameters:
-
rational(bool, default:True) –If True, applies rational simplification to the matrix entries using
sym.nsimplify. -
suppress_warnings(bool, default:False) –If True, suppresses warnings about non-zero residues after rational simplification.
-
tolerance(float, default:0.0001) –The tolerance for rational simplification.
-
simplify(bool, default:True) –If True, applies general symbolic simplification using
sym.simplify. -
expand(bool, default:True) –If True, applies expansion to the matrix entries. If False, applies factoring instead.
-
collect_sym(Symbol, default:None) –A symbol to collect terms with. If provided,
sym.collectwill be applied to all entries of the matrix with respect to this symbol. -
*args–Additional arguments passed to the
sym.simplifyfunction. -
**kwargs–Additional arguments passed to the
sym.simplifyfunction.
Returns:
-
Matrix–A new simplified matrix with the applied operations.
Examples:
| Python Console Session | |
|---|---|
Source code in src/ma1522/symbolic.py
| Python | |
|---|---|
697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 | |
identify(tol: float | None = None, suppress_warnings: bool = False, *args, **kwargs) -> Matrix
¶
Identifies the matrix by applying a transformation function to each entry.
This method applies a transformation to each element of the matrix using
the identify function from the mp module. After identification,
the method checks if there is any residue (i.e., if the matrix has been modified).
Note
- If there is a residue (i.e., unable to identify an entry, such as \(\pi\)),
a warning is printed with the approximation error. This can be resolved by
lowering
toleranceor supplying appropriateconstantsas**kwargsto theidentifyfunction.
Parameters:
-
tol(float, default:None) –A tolerance value that is passed to the
identifyfunction. If None, no tolerance is applied. -
suppress_warnings(bool, default:False) –If True, suppresses warnings about non-zero residues after identification.
-
*args–Additional positional arguments passed to the
identifyfunction. -
**kwargs–Additional keyword arguments passed to the
identifyfunction.
Returns:
-
Matrix–A new matrix that results from applying the transformation to each element of the original matrix.
Examples:
| Python Console Session | |
|---|---|
See Also
mpmath.identify: The function used to identify the entries of the matrix.simplify: For general simplification of the matrix entries.
Source code in src/ma1522/symbolic.py
select_cols(*args: int) -> Matrix
¶
Selects columns from the matrix based on the provided column indices.
This method returns a new matrix consisting of the columns specified by the provided indices. The columns are selected from the original matrix, and the result is returned as a new matrix.
Parameters:
-
*args(int, default:()) –One or more column indices (0-based) to select from the matrix.
Returns:
-
Matrix–A new matrix consisting of the selected columns.
Examples:
| Python Console Session | |
|---|---|
Source code in src/ma1522/symbolic.py
select_rows(*args: int) -> Matrix
¶
Selects rows from the matrix based on the provided row indices.
This method returns a new matrix consisting of the rows specified by the provided indices. The rows are selected from the original matrix, and the result is returned as a new matrix.
Parameters:
-
*args(int, default:()) –One or more row indices (0-based) to select from the matrix.
Returns:
-
Matrix–A new matrix consisting of the selected rows.
Examples:
| Python Console Session | |
|---|---|
Source code in src/ma1522/symbolic.py
sep_part_gen() -> PartGen
¶
Separates a matrix into its particular and general solution parts.
This method separates the matrix into two components
- The particular solution, which is the solution to the system when all free variables are set to zero.
- The general solution, which is the full solution including the homogeneous part.
It assumes that the matrix is in symbolic form and contains free variables that can be set to zero.
Returns:
-
PartGen–
Examples:
| Python Console Session | |
|---|---|
Source code in src/ma1522/symbolic.py
sep_unk() -> dict[Expr, Matrix]
¶
Separates the matrix into matrices with each free symbol set to 1.
Returns:
-
dict[Expr, Matrix]–Returns a dictionary where the sum of the key*value pairs reconstructs the original matrix. Each key is a free symbol, and each value is a matrix with that symbol set to 1 and all other free symbols set to 0.
Examples:
| Python Console Session | |
|---|---|
Source code in src/ma1522/symbolic.py
scalar_factor(column: bool = True) -> ScalarFactor
¶
Factorizes a matrix into the form \(\mathbf{A} = \mathbf{FD}\), where \(\mathbf{D}\) is a diagonal matrix
and \(\mathbf{F}\) contains the vectors with common divisors factored out (if column=True). If column=False,
then returns \(\mathbf{A} = \mathbf{DF}\) instead.
Parameters:
-
column(bool, default:True) –If
True, factorizes by columns. IfFalse, factorizes by rows.
Returns:
-
ScalarFactor–A dataclass of two matrices (F, D) and order (FD or DF)
Examples:
| Python Console Session | |
|---|---|
Source code in src/ma1522/symbolic.py
aug_line(pos: int = -1) -> Matrix
¶
Inserts an augmented line at the specified position.
This method adds an augmented line (i.e., a visual vertical line) to the matrix at the specified column position. If no position is provided (default: -1), the line is inserted at the last column.
Note
- The method updates the
_aug_posattribute to track the position of the inserted line. - Negative
poswill be converted before inserting it into_aug_pos.
Parameters:
-
pos(int, default:-1) –The position (column index) where the augmented line will be inserted. Default -1 means the augmented line is added at the end of the matrix.
Returns:
-
Matrix–The current matrix with the augmented line added at the specified position.
Raises:
-
IndexError–If the
posis out of range.
Examples:
| Python Console Session | |
|---|---|
| Python Console Session | |
|---|---|
See Also
rm_aug_line: Removes an augmentation line from the matrix.
Source code in src/ma1522/symbolic.py
rm_aug_line(pos: int | None = None) -> Matrix
¶
Remove an augmentation line from the matrix.
Removes the specified position from the matrix's augmentation line tracking. If the matrix has no augmentation lines tracked or the position is not currently marked as an augmentation line, the matrix remains unchanged.
Note
This method modifies the matrix's internal _aug_pos attribute which
tracks augmentation line positions. If no _aug_pos attribute exists,
it will be initialized as an empty set.
Parameters:
-
pos(int, default:None) –The column position of the augmentation line to remove. If it is not set, all augmentation lines will be removed
Returns:
-
Matrix–The matrix instance (supports method chaining).
Examples:
| Python Console Session | |
|---|---|
Source code in src/ma1522/symbolic.py
row_join(other: Matrix, aug_line: bool = True) -> Matrix
¶
Joins two matrices horizontally (column-wise), preserving augmentation lines.
This method concatenates the columns of self and other to form a new matrix. Any augmentation lines
(vertical lines for augmented matrices) tracked in either matrix are preserved and adjusted for the new column positions.
Parameters:
-
other(Matrix) –The matrix to join to the right of
self. -
aug_line(bool, default:True) –If
True, adds an augmentation line between the two matrices.
Returns:
-
Matrix–A new matrix formed by joining
selfandothercolumn-wise, with updated augmentation lines.
Raises:
-
ShapeError–If the number of rows in
selfandotherdo not match.
Examples:
| Python Console Session | |
|---|---|
Source code in src/ma1522/symbolic.py
col_join(other: Matrix) -> Matrix
¶
Joins two matrices vertically (row-wise), preserving augmentation lines.
This method concatenates the rows of self and other to form a new matrix. Only augmentation lines
(vertical lines for augmented matrices) that are present in both matrices at the same column positions are preserved.
Note
- Both
selfandothermatrices should have the same number of columns for the join to be valid. - The method updates the
_aug_posattribute to include only those positions that are common in both matrices, ensuring that the augmentation lines are correctly aligned after the join.
Parameters:
-
other(Matrix) –The matrix to join below
self.
Returns:
-
Matrix–A new matrix formed by joining
selfandotherrow-wise, with preserved augmentation lines.
Raises:
-
ShapeError–If the number of columns in
selfandotherdo not match.
Examples:
| Python Console Session | |
|---|---|
Source code in src/ma1522/symbolic.py
scale_row(idx: int, scalar: Expr | float | int, verbosity: int = 2) -> Matrix
¶
Scales a row of the matrix by a scalar and simplifies the result.
This method scales a specified row of the matrix by multiplying it with a scalar and then simplifies the matrix. The result is stored back in the matrix. Optionally, the method can print information about the row scaling and display the matrix, depending on the verbosity level.
Note
- The method modifies the matrix in-place and returns the updated matrix.
- After scaling the row, the matrix is simplified using
simplify.
Parameters:
-
idx(int) –The index of the row to scale (0-based).
-
scalar((Expr, float, int)) –The scalar by which to multiply the row.
-
verbosity(int, default:2) –The level of verbosity for output.
- 0: No output.
- 1: Print the row scaling operation.
- 2: Print the row scaling operation and display the matrix.
Returns:
-
Matrix–The modified matrix with the scaled row.
Raises:
-
IndexError–If the
idxis out of range for the number of rows in the matrix.
Examples:
| Python Console Session | |
|---|---|
Source code in src/ma1522/symbolic.py
swap_row(idx_1: int, idx_2: int, verbosity: int = 2) -> Matrix
¶
Swaps two rows of the matrix.
This method swaps the contents of two rows in the matrix. The operation is performed in-place, and the modified matrix is returned. Optionally, the method can print information about the row swap and display the matrix, depending on the verbosity level.
Note
- The method modifies the matrix in-place and returns the updated matrix.
- After performing the row swaps, the matrix is simplified using
simplify.
Parameters:
-
idx_1(int) –The index of the first row to swap (0-based).
-
idx_2(int) –The index of the second row to swap (0-based).
-
verbosity(int, default:2) –The level of verbosity for output.
- 0: No output.
- 1: Print the row swap operation.
- 2: Print the row swap operation and display the matrix.
Returns:
-
Matrix–The modified matrix after the row swap.
Raises:
-
IndexError–If the
idx_1oridx_2is out of range for the number of rows in the matrix.
Examples:
| Python Console Session | |
|---|---|
Source code in src/ma1522/symbolic.py
reduce_row(idx_1: int, scalar: Expr | float | int, idx_2: int, verbosity: int = 2) -> Matrix
¶
Reduces a row by subtracting a scalar multiple of another row.
This method modifies a row by subtracting a specified scalar multiple of another row. The result is stored back in the matrix. Optionally, the method can print information about the row reduction and display the matrix, depending on the verbosity level.
Note
- The method modifies the matrix in-place and returns the updated matrix.
- After performing the row reduction, the matrix is simplified using
simplify.
Parameters:
-
idx_1(int) –The index of the row to reduce (0-based).
-
scalar((Expr, float, int)) –The scalar by which to multiply the second row.
-
idx_2(int) –The index of the row from which to subtract the scalar multiple (0-based).
-
verbosity(int, default:2) –The level of verbosity for output.
- 0: No output.
- 1: Print the row reduction operation.
- 2: Print the row reduction operation and display the matrix.
Returns:
-
Matrix–The modified matrix after the row reduction.
Raises:
-
IndexError–If the
idx_1oridx_2is out of range for the number of rows in the matrix.
Examples:
| Python Console Session | |
|---|---|
Source code in src/ma1522/symbolic.py
get_pivot_row(col_idx: int, row_start_idx: int, follow_GE: bool = False) -> int | None
¶
Finds the row index of the pivot element in a given column.
This method attempts to find a row that contains a non-zero element in the
specified column. If the follow_GE flag is False, it first looks for
a non-zero constant that does not contain any symbolic expressions. If no
such element is found, it will return the first non-zero element. If the
entire column contains only zeros, the method returns -1.
Parameters:
-
col_idx(int) –The index of the column to search for the pivot.
-
row_start_idx(int) –The row index to start searching from.
-
follow_GE(bool, default:False) –Flag to control whether to follow Gaussian elimination strategy.
True: Always return the first non-zero element, even if it is symbolic.False: First look for non-zero constants that are not symbolic expressions.
Returns:
-
int–The index of the row containing the pivot element, or None if no pivot is found.
Examples:
| Python Console Session | |
|---|---|
Source code in src/ma1522/symbolic.py
get_pivot_pos() -> list[tuple[int, int]]
¶
Finds the positions of the pivot elements in the matrix.
This method checks the matrix to determine the positions of the pivots
(the first non-zero entry in each row) by examining each column one-by-one.
It assumes that the matrix is in Row Echelon Form (REF), as checked by the
is_echelon property.
It uses get_pivot_row to find the pivot row for each column.
For each pivot found, a tuple (row, column) is added to the result list.
Returns:
-
list[tuple[int, int]]–A list of lists, where each sublist contains a tuple representing the position (row, column) of a pivot.
Examples:
| Python Console Session | |
|---|---|
Source code in src/ma1522/symbolic.py
get_pivot_elements() -> list[sym.Expr]
¶
Retrieves the pivot elements from the matrix.
This method identifies the pivot positions (row, column) using the
get_pivot_pos method and
then extracts the elements at those positions in the matrix.
Returns:
-
list[Expr]–A list of pivot elements corresponding to the positions identified by
get_pivot_pos.
Examples:
| Python Console Session | |
|---|---|
Source code in src/ma1522/symbolic.py
ref(verbosity: int = 2, max_tries: int = 2, follow_GE: bool = False) -> PLU
¶
Find the Row Echelon Form (REF) of the matrix.
This method applies Gaussian elimination (or a similar approach) to bring the matrix to row echelon form.
Note
- PLU decomposition is the generalisation of the LU decomposition. Unlike LU decomposition, PLU works for any matrix.
- The REF is obtained from
PLU.Uand the matrix is LU factorisable ifPLU.Pis the identity matrix.
Parameters:
-
verbosity(int, default:2) –Level of verbosity for the output.
- 0: No output.
- 1: Output basic information (e.g., row operations).
- 2: Output detailed information (e.g., matrix states after each operation).
-
max_tries(int, default:2) –Maximum number of tries to reduce a row in case of symbolic denominators.
-
follow_GE(bool, default:False) –Whether to strictly follow Gaussian elimination rules.
True: Always return the first non-zero element, even if it is symbolic.False: First look for non-zero constants that are not symbolic expressions.
Returns:
-
PLU–
Examples:
| Python Console Session | |
|---|---|
See Also
Source code in src/ma1522/symbolic.py
| Python | |
|---|---|
1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 | |
evaluate_cases(rhs: Matrix | None = None, verbosity: int = 0) -> list[RREFCase]
¶
Evaluates and displays all possible cases for solutions to a linear system involving the matrix.
This method uses rref_cases to find symbolic cases, and group them
based on the system's outcome (no solution, unique solution, infinitely many solutions).
- Merge redundant cases with identical outcomes only when a less- specific case explicitly excludes the dropped assignment(s).
- Order results by outcome priority:
- No solution
- Unique solution
- Infinitely many solutions (increasing free parameters)
Parameters:
-
rhs(Matrix, default:None) –The right-hand side of the system Ax = rhs. If not provided, the system is treated as homogeneous.
-
verbosity(int, default:0) –The level of verbosity for the computation.
Returns:
-
list[RREFCase]–The merged and ordered list of symbolic RREF cases found by
rref_cases.
Examples:
| Python Console Session | |
|---|---|
See Also
rref_cases: Returns case data without printing a summary or merging similar cases.
Source code in src/ma1522/symbolic.py
| Python | |
|---|---|
1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 | |
rref(*args, pivots: bool = True, **kwargs) -> RREF | Matrix
¶
Computes the Reduced Row Echelon Form (RREF) of the matrix.
This method is a wrapper for rref method
and returns the matrix in Reduced Row Echelon Form (RREF) along with the pivot positions.
Parameters:
-
pivots(bool, default:True) –If
True, returns a tuple containing the RREF matrix and a list of pivot columns -
*args–Positional arguments passed to SymPy's
rrefmethod. -
**kwargs–Keyword arguments passed to SymPy's
rrefmethod.
Returns:
Examples:
| Python Console Session | |
|---|---|
Source code in src/ma1522/symbolic.py
rref_cases(rhs: Matrix | None = None, verbosity: int = 0) -> list[RREFCase]
¶
Compute all symbolic-RREF cases by splitting on zero-pivot conditions.
When the matrix contains free symbols, different assignments of those
symbols can lead to structurally different row-echelon forms (different
numbers of pivots, inconsistencies, etc.). This method detects exactly
those critical values by branching at every pivot that could be zero,
and returns one RREFCase per distinct branch.
Algorithm:
- Work column-by-column to find the leftmost pivot in each active row.
- If the candidate pivot entry has free symbols that can equal zero,
create two branches:
- Zero branch: substitute the zero-making values and retry the same column (a different row may now become the pivot).
- Non-zero branch: treat the entry as a non-zero (possibly symbolic) scalar, normalise the pivot row to 1, and eliminate the pivot column in all other rows (full RREF).
- Recursion terminates when all columns (or rows) have been processed.
Parameters:
-
rhs(Matrix, default:None) –Right-hand side of the system
Ax = rhs, appended as an augmented column block. When provided, eachRREFCasereports consistency inRREFCase.is_consistent. -
verbosity(int, default:0) –Level of verbosity for the computation.
Returns:
-
list[RREFCase]–One entry per distinct case. Each
RREFCasecontains:conditions— the symbol substitutions that define the case.excluded— zero-conditions from other cases (i.e. what is not assumed here), excluding redundant alternatives for symbols already fixed byconditions.rref— the RREF matrix (augmented if rhs was given).pivots— pivot column indices.free_params— number of free parameters.is_consistent—True/False(Noneif no rhs).
Examples:
Pure homogeneous system with one parameter:
| Python Console Session | |
|---|---|
Non-homogeneous system also checks consistency:
| Python Console Session | |
|---|---|
See Also
rreffor the standard (non-branching) RREF wrapper.evaluate_casesfor a printing-oriented case analysis.
Source code in src/ma1522/symbolic.py
| Python | |
|---|---|
2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 | |
solve(rhs: Matrix, verbosity: int = 0) -> list[Matrix]
¶
Solves the linear system Ax = rhs for x.
This method uses SymPy's solve method to find a solution vector x such that self @ x = rhs.
A list of solution matrices is returned.
If no solution exists (e.g., the system is inconsistent), a ValueError is raised.
Parameters:
-
rhs(Matrix) –The right-hand side matrix or vector in the equation
Ax = rhs. -
verbosity(int, default:0) –Level of verbosity for displaying intermediate steps: - 0: No output. - 1: Display the augmented matrix before and after RREF.
Returns:
Raises:
-
ValueError–If no solution is found for the linear system, an exception is raised.
Examples:
| Python Console Session | |
|---|---|
See Also
sympy.solve: For solving equations in general.rref: For finding the reduced row echelon form of the matrix.solve_least_squares: For solving least squares problems.
Source code in src/ma1522/symbolic.py
inverse(option: Literal['left', 'right', 'both'] | None = None, matrices: int = 1, verbosity: int = 0) -> Matrix | PartGen | None
¶
Computes the left or right inverse of a matrix, depending on its rank and the specified option.
The method checks whether the matrix has full row rank or full column rank and computes either
- The left inverse (if the matrix has full column rank).
- The right inverse (if the matrix has full row rank).
If neither option is provided, the method automatically determines which inverse to compute based on the matrix's rank.
Parameters:
-
option(str, default:None) –Specifies which inverse to compute:
'left'for the left inverse (requires the matrix to have full column rank).'right'for the right inverse (requires the matrix to have full row rank).'both'for the inverse of a square matrix (works on both sides).
-
matrices(int, default:1) –Specifies the number of matrices to return:
- 1: Returns only the inverse matrix.
- 2: Returns the particular and general solutions of the inverse.
-
verbosity(int, default:0) –Level of verbosity for displaying intermediate steps:
- 0: No output.
- 1: Display matrices before and after RREF.
Returns:
-
Matrix–If
matrices = 1, returns the inverse matrix. -
PartGen–If
matrices = 2, returns a dataclass containing the particular and general solutions of the inverse.
Raises:
-
ValueError–If no valid inverse (left or right or both) is found, an exception is raised.
Examples:
| Python Console Session | |
|---|---|
Source code in src/ma1522/symbolic.py
| Python | |
|---|---|
2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331 2332 2333 2334 2335 2336 2337 2338 2339 2340 2341 2342 2343 2344 2345 2346 2347 2348 2349 2350 2351 2352 2353 2354 2355 2356 2357 2358 2359 2360 2361 2362 2363 2364 2365 2366 2367 2368 2369 2370 2371 2372 2373 2374 2375 2376 2377 2378 2379 | |
elem() -> Matrix
¶
Returns the identity matrix with the same number of rows as the current matrix.
This method creates an identity matrix to be used for elementary row operations,
i.e., A = I A where I is the identity matrix.
Returns:
-
Matrix–An identity matrix with the same number of rows as the current matrix.
Examples:
| Python Console Session | |
|---|---|
Source code in src/ma1522/symbolic.py
adjoint() -> Matrix
¶
Computes the adjugate (classical adjoint) of the matrix.
This method calculates the classical adjoint (also known as the adjugate in literature) of the matrix. The adjoint of a matrix (as defined in MA1522 syllabus) is the transpose of its cofactor matrix.
Note
If you wish to compute the conjugate transpose of the matrix (SymPy's definition for adjoint),
use self.H directly or super(symbolic.Matrix, self).adjoint() to call the parent method.
Returns:
-
Matrix–The classical adjoint (or adjugate) matrix of the current matrix.
Examples:
| Python Console Session | |
|---|---|
See Also
- SymPy's
Matrix.adjugate - SymPy's
Matrix.adjointfor conjugate transpose.
Source code in src/ma1522/symbolic.py
adj(method: Literal['bareiss', 'berkowitz', 'bird', 'laplace', 'lu'] = 'berkowitz') -> Matrix
¶
Alias for the adjoint method.
It returns the classical adjoint (or adjugate) of the matrix.
Parameters:
-
method(str, default:'berkowitz') –Method to use to find the cofactors, can be "bareiss", "berkowitz", "bird", "laplace" or "lu".
Returns: (Matrix): The classical adjoint of the current matrix.
Examples:
| Python Console Session | |
|---|---|
See Also
- SymPy's
adjugate
Source code in src/ma1522/symbolic.py
cramer_solve(rhs: Matrix, det_method: str = 'laplace', verbosity: int = 2) -> Matrix
¶
Solves the linear system using Cramer's Rule.
This method applies Cramer's Rule to solve the linear system represented by the matrix and the right-hand side vector. It computes the determinant of the matrix and uses it to find the solution vector.
Parameters:
-
rhs(Matrix) –The right-hand side vector in the equation
Ax = rhs. -
det_method(str, default:'laplace') –The method to use for computing the determinant. Options include:
'laplace': Uses the Laplace expansion method.'berkowitz': Uses the Berkowitz algorithm.'bird': Uses the Bird's algorithm.'bareiss': Uses the Bareiss algorithm.'lu': Uses LU decomposition.
-
verbosity(int, default:2) –Level of verbosity for displaying intermediate steps:
- 0: No output.
- 1: Display basic information.
- 2: Display detailed information.
Returns:
-
Matrix–The solution vector
xthat satisfiesself @ x = rhs.
Raises:
-
NonSquareMatrixError–If the matrix is not square.
-
ShapeError–If the matrix and the right-hand side vector have incompatible dimensions.
-
ValueError–If the determinant is zero, indicating that the system has no unique solution.
Examples:
| Python Console Session | |
|---|---|
See Also
solve: For solving linear systems using other methods.- SymPy's
Matrix.detfor computing the determinant. - SymPy's
Matrix.cramer_solve
Source code in src/ma1522/symbolic.py
| Python | |
|---|---|
2463 2464 2465 2466 2467 2468 2469 2470 2471 2472 2473 2474 2475 2476 2477 2478 2479 2480 2481 2482 2483 2484 2485 2486 2487 2488 2489 2490 2491 2492 2493 2494 2495 2496 2497 2498 2499 2500 2501 2502 2503 2504 2505 2506 2507 2508 2509 2510 2511 2512 2513 2514 2515 2516 2517 2518 2519 2520 2521 2522 2523 2524 2525 2526 2527 2528 2529 2530 2531 2532 2533 2534 2535 2536 2537 2538 2539 2540 2541 2542 2543 | |
column_constraints(use_ref: bool = False, verbosity: int = 1) -> Matrix
¶
Computes the column constraints for the matrix by appending a symbolic vector.
This method creates a matrix where a random column vector \(\begin{pmatrix} x_1 \\ \vdots \\ x_m \end{pmatrix}\) is added to the matrix as an additional column. It then constructs a larger augmented matrix and optionally computes its Row Echelon Form (REF) or Reduced Row Echelon Form (RREF).
The method modifies the matrix to ensure that the unknown vector is not reduced in RREF, and the constraints for the matrix columns are calculated accordingly.
Parameters:
-
use_ref(bool, default:False) –Whether to use Row Echelon Form (REF) instead of Reduced Row Echelon Form (RREF). If
False, RREF will be used. -
verbosity(int, default:1) –Verbosity level for displaying information.
- 0: No output
- 1: Display all information
Returns:
-
Matrix–A new matrix containing the result after applying REF or RREF to the augmented matrix.
Examples:
| Python Console Session | |
|---|---|
| Python Console Session | |
|---|---|
Source code in src/ma1522/symbolic.py
| Python | |
|---|---|
2545 2546 2547 2548 2549 2550 2551 2552 2553 2554 2555 2556 2557 2558 2559 2560 2561 2562 2563 2564 2565 2566 2567 2568 2569 2570 2571 2572 2573 2574 2575 2576 2577 2578 2579 2580 2581 2582 2583 2584 2585 2586 2587 2588 2589 2590 2591 2592 2593 2594 2595 2596 2597 2598 2599 2600 2601 2602 2603 2604 2605 2606 2607 2608 2609 | |
normalized(iszerofunc: Callable[[Expr], int] | None = None, factor: bool = False) -> Matrix | ScalarFactor
¶
Normalizes the column vectors of the matrix (scaling each vector to have a unit norm).
Parameters:
-
iszerofunc(Callable[[Expr], int], default:None) –Function to determine if a value should be treated as zero
-
factor(bool, default:False) –If
True, returns theScalarFactordataclass. IfFalse, only the normalized matrix is returned.
Returns:
-
ScalarFactor–A dataclass containing the normalized matrix and the diagonal matrix of norms if
factor=True. -
Matrix–The normalized matrix if
factor=False.
Examples:
| Python Console Session | |
|---|---|
| Python Console Session | |
|---|---|
Source code in src/ma1522/symbolic.py
is_linearly_independent(colspace: bool = True, verbosity: int = 0) -> bool
¶
Determines if the vectors in the matrix are linearly independent.
This method checks whether the columns (or rows) of the matrix are linearly independent by computing its reduced row echelon form (RREF) and comparing the number of pivot columns to the number of columns (or rows).
Parameters:
-
colspace(bool, default:True) –If
True, checks linear independence of columns (column space). IfFalse, checks linear independence of rows (row space). -
verbosity(int, default:0) –Level of output during the RREF and check.
- 0: No output (default).
- 1: Print summary of the RREF and check.
- 2: Print the matrix before and after RREF, and the check details.
Returns:
-
bool–Trueif the matrix's columns (or rows) are linearly independent,Falseotherwise.
Examples:
| Python Console Session | |
|---|---|
| Python Console Session | |
|---|---|
Source code in src/ma1522/symbolic.py
get_linearly_independent_vectors(colspace: bool = True, verbosity: int = 1) -> Matrix
¶
Returns a matrix containing the linearly independent vectors from the column space or row space.
This method computes the reduced row echelon form (RREF) of the matrix and selects the non-zero rows as linearly independent vectors. The result is a matrix whose columns (or rows) are linearly independent.
Parameters:
-
colspace(bool, default:True) –If
True, returns linearly independent vectors from the column space. IfFalse, returns from the row space. -
verbosity(int, default:1) –Level of output verbosity.
- 0: No output.
- 1: Print a summary of the RREF and selection.
Returns:
-
Matrix–A matrix whose columns (if colspace=True) or rows (if colspace=False) are linearly independent vectors.
Examples:
| Python Console Session | |
|---|---|
Source code in src/ma1522/symbolic.py
simplify_basis(colspace: bool = True, verbosity: int = 2) -> Matrix
¶
Returns a simplified basis for the column space or row space of the matrix.
This method computes a basis for either the column space or the row space of the matrix by reducing the matrix (or its transpose) to reduced row echelon form (RREF) and selecting the nonzero rows as basis vectors. The result is a matrix whose columns (or rows) form a basis for the specified subspace.
Parameters:
-
colspace(bool, default:True) –If
True, returns a basis for the column space. IfFalse, returns a basis for the row space. -
verbosity(int, default:2) –Level of output verbosity.
- 0: No output.
- 1: Print a summary of the RREF and basis selection.
- 2: Print the matrix before and after RREF, and show the selected basis vectors.
Returns:
-
Matrix–A matrix whose columns (if colspace=True) or rows (if colspace=False) form a basis for the corresponding subspace.
Examples:
| Python Console Session | |
|---|---|
| Python Console Session | |
|---|---|
Source code in src/ma1522/symbolic.py
| Python | |
|---|---|
2770 2771 2772 2773 2774 2775 2776 2777 2778 2779 2780 2781 2782 2783 2784 2785 2786 2787 2788 2789 2790 2791 2792 2793 2794 2795 2796 2797 2798 2799 2800 2801 2802 2803 2804 2805 2806 2807 2808 2809 2810 2811 2812 2813 2814 2815 2816 2817 2818 2819 2820 2821 2822 2823 2824 2825 2826 2827 2828 2829 2830 2831 2832 2833 2834 2835 2836 2837 | |
extend_basis(span_subspace: Matrix | None = None, verbosity: int = 2) -> Matrix
¶
Extends the matrix to form a basis for the span of the given subspace.
This method extends the column space of the current matrix to include the columns of the provided
span_subspace, computes the Reduced Row Echelon Form (RREF) of the augmented matrix,
and then selects the pivot columns to return the extended basis.
If no span_subspace is provided, the identity matrix (i.e. \(\mathrm{span} \left(\mathbb{R}^n \right)\)) is used as the default.
The result is a matrix with the extended basis that spans the combined space of the self
matrix and the span_subspace.
Parameters:
-
span_subspace(Matrix, default:None) –A matrix whose columns represent the subspace to be added to the current matrix. If
None, the identity matrix is used. -
verbosity(int, default:2) –Verbosity level for displaying information.
- 0: No output.
- 1: Display steps.
- 2: Display the matrix before and after RREF.
Returns:
-
Matrix–A matrix whose column space represents the extended basis, consisting of the pivot columns from the RREF of the augmented matrix.
Examples:
| Python Console Session | |
|---|---|
Source code in src/ma1522/symbolic.py
intersect_subspace(other: Matrix, verbosity: int = 2) -> Matrix
¶
Computes the intersection of two subspaces by finding the nullspace of their orthogonal complements.
This method computes the intersection of the subspaces spanned by the columns of the current matrix
(self) and the provided matrix (other). The intersection is computed by finding the union of the nullspace of
the row space of the two matrices, and then finding its orthogonal complement.
Parameters:
-
other(Matrix) –The second matrix representing the other subspace to intersect with the current matrix.
-
verbosity(int, default:2) –Level of verbosity for displaying intermediate steps:
- 0: No output.
- 1: Display steps.
- 2: Display the relevant matrices. Defaults to 2.
Returns:
-
Matrix–A matrix whose columns form a basis for the intersection of the two subspaces.
Examples:
| Python Console Session | |
|---|---|
Source code in src/ma1522/symbolic.py
is_subspace_of(other: Matrix, verbosity: int = 2) -> bool
¶
Checks if the current matrix is a subspace of another matrix.
This method determines whether the subspace spanned by the columns of the current matrix (self)
is a subspace of the provided matrix (other). It does so by checking if the row-reduced echelon form
(RREF) of the augmented matrix [other | self].
Parameters:
-
other(Matrix) –The second matrix representing the other subspace to compare with the current matrix. If
None, the identity matrix is used to check if it spans \(\mathbb{R}^\text{self.rows}}\) -
verbosity(int, default:2) –Level of verbosity for displaying intermediate steps:
- 0: No output.
- 1: Display the steps.
- 2: Display the relevant matrices.
Returns:
-
bool–Trueif the subspace spanned byselfis a subspace ofother,Falseotherwise.
Raises:
-
ShapeError–If the number of rows in the current matrix and the target matrix are different.
Examples:
| Python Console Session | |
|---|---|
Source code in src/ma1522/symbolic.py
is_same_subspace(other: Matrix | None = None, verbosity: int = 2) -> bool
¶
Checks if two subspaces are the same by verifying if each subspace is a subspace of the other.
This method determines whether the subspaces spanned by the columns of the current matrix (self)
and the provided matrix (other) are the same. It does so by calling the is_subspace_of method
twice: first to check if self is a subspace of other, and then to check if other is a subspace of self.
If both checks return True, then the subspaces are considered the same.
Parameters:
-
other(Matrix, default:None) –The second matrix representing the other subspace to compare with the current matrix. If
None, the identity matrix is used to check if it spans \(\mathbb{R}^\text{self.rows}}\) -
verbosity(int, default:2) –Level of verbosity for displaying intermediate steps:
- 0: No output.
- 1: Display the steps.
- 2: Display the relevant matrices. Defaults to 2.
Returns:
-
bool–Trueif the subspaces spanned byselfandotherare the same,Falseotherwise.
Raises:
-
ShapeError–If the number of rows in the current matrix and the target matrix are different.
Examples:
| Python Console Session | |
|---|---|
Source code in src/ma1522/symbolic.py
coords_relative(basis: Matrix, verbosity: int = 2) -> Matrix
¶
Computes the coordinates of the current vector relative to a given basis.
This method finds the coordinate vector c such that self = basis @ c,
where basis is a matrix whose columns form a basis, and self is a column vector. The method
achieves this by augmenting the target matrix with the current matrix, performing
Reduced Row Echelon Form (RREF), and extracting the appropriate part of the resulting matrix.
Parameters:
-
basis(Matrix) –The matrix whose columns form the target basis.
-
verbosity(int, default:2) –Level of output verbosity.
- 0: No output.
- 1: Print summary of the RREF and solution.
- 2: Print the matrix before and after RREF, and show the solution details.
Returns:
-
Matrix–The coordinate vector of
selfrelative to the basisto.
Raises:
-
ShapeError–If
selfis not a column vector or if the number of rows inselfandbasisdo not match. -
ValueError–If the system is inconsistent and no solution exists.
Examples:
| Python Console Session | |
|---|---|
Source code in src/ma1522/symbolic.py
| Python | |
|---|---|
3059 3060 3061 3062 3063 3064 3065 3066 3067 3068 3069 3070 3071 3072 3073 3074 3075 3076 3077 3078 3079 3080 3081 3082 3083 3084 3085 3086 3087 3088 3089 3090 3091 3092 3093 3094 3095 3096 3097 3098 3099 3100 3101 3102 3103 3104 3105 3106 3107 3108 3109 3110 3111 3112 3113 3114 3115 3116 3117 3118 3119 3120 | |
transition_matrix(to: Matrix, verbosity: int = 2) -> Matrix
¶
Computes the transition matrix that transforms this matrix to another matrix.
This method computes the transition matrix P such that self = P @ to,
where to is the target basis, and self is the current basis. The method
achieves this by augmenting the target matrix with the current matrix, performing
Reduced Row Echelon Form (RREF), and extracting the appropriate part of the resulting matrix.
Parameters:
-
to(Matrix) –The matrix to which the current matrix should be transformed.
-
verbosity(int, default:2) –Verbosity level for displaying information.
- 0: No output.
- 1: Display the steps.
- 2: Display the relevant matrices.
Returns:
-
Matrix–The transition matrix
Pthat satisfiesself = P @ to.
Raises:
-
AssertionError–If the columns of the
selfmatrix andtomatrix do not span the same subspace.
Examples:
| Python Console Session | |
|---|---|
Source code in src/ma1522/symbolic.py
nullspace(verbosity: int = 0, *args, **kwargs) -> list[Matrix]
¶
Computes the null space (kernel) of the matrix, i.e., the set of vectors that satisfy self @ x = 0.
This method utilizes the rank-nullity theorem to determine if the null space exists. Fixes the issue with SymPy implementation of nullspace where it raises an exception if the nullspace is trivial (only contain the zero vector). If the matrix has full column rank (i.e., rank = number of columns), it has no non-trivial null space, and an empty list is returned.
Parameters:
-
verbosity(int, default:0) –Level of verbosity for displaying intermediate steps.
- 0: No output.
- 1: Display the matrix before and after row-reduction (RREF).
-
*args–Additional positional arguments passed to SymPy's
nullspacemethod. -
**kwargs–Additional keyword arguments passed to SymPy's
nullspacemethod.
Returns:
-
list[Matrix]–list[Matrix]: A list of
Matrixobjects representing the null space vectors. Returns an empty list if the null space is trivial.
Examples:
| Python Console Session | |
|---|---|
See Also
- SymPy's
Matrix.nullspace orthogonal_complementfor computing the orthogonal complement of the matrix.
Source code in src/ma1522/symbolic.py
nullity() -> int
¶
Computes the nullity of the matrix, which is the dimension of its null space.
The nullity is defined as the number of free variables in the solution to the homogeneous equation self @ x = 0.
It can be computed as nullity = cols - rank, where cols is the number of columns in the matrix and rank is its rank.
Returns:
-
int–The nullity of the matrix.
Examples:
Source code in src/ma1522/symbolic.py
orthogonal_complement(verbosity: int = 0) -> Matrix
¶
Computes the orthogonal complement of the matrix (the null space of its transpose).
The orthogonal complement consists of all vectors that are orthogonal to the column space of the matrix. This method computes the null space of the transpose of the matrix, which gives a basis for the orthogonal complement.
Note
The orthogonal complement is the set of all vectors v such that self^T @ v = 0.
Parameters:
-
verbosity(int, default:0) –Level of verbosity for debugging.
- 0: No output.
- 1: Display the matrix before and after row-reduction (RREF).
Returns:
-
Matrix–A matrix whose columns form a basis for the orthogonal complement.
Examples:
| Python Console Session | |
|---|---|
Source code in src/ma1522/symbolic.py
is_vec_orthogonal(verbosity: int = 1) -> bool
¶
Checks if the column vectors of the matrix are orthogonal to each other.
This method computes self^T @ self and checks if the result is diagonal.
If the result is diagonal, the vectors are orthogonal (i.e., \(u_i \dot u_j = 0 \forall i != j\)).
Note
This method checks for orthogonality, not orthonormality. For orthonormality, use is_mat_orthogonal.
Parameters:
-
verbosity(int, default:1) –Level of verbosity for displaying intermediate results.
- 0: No output.
- 1: Display the matrix product
self.T @ self.
Returns:
-
bool–Trueif the column vectors are orthogonal,Falseotherwise.
Examples:
| Python Console Session | |
|---|---|
Source code in src/ma1522/symbolic.py
is_mat_orthogonal(verbosity: int = 1) -> bool
¶
Checks if the matrix is orthogonal (i.e., its columns are orthonormal).
A matrix is orthogonal if its columns are orthonormal, i.e., if self.T @ self is the identity matrix.
This method computes self.T @ self and checks if the result is an identity matrix.
Parameters:
-
verbosity(int, default:1) –Level of verbosity for displaying intermediate results.
- 0: No output.
- 1: Display the matrix product
self.T @ self.
Returns:
-
bool–True if the matrix is orthogonal, False otherwise.
Examples:
| Python Console Session | |
|---|---|
| Python Console Session | |
|---|---|
Source code in src/ma1522/symbolic.py
orthogonal_decomposition(to: Matrix, verbosity: int = 0) -> VecDecomp
¶
Decomposes the current vector (or matrix) into its orthogonal projection onto a subspace and its orthogonal complement.
This method computes the orthogonal decomposition of self relative to the subspace spanned by the columns of to.
It finds the projection of self onto the subspace (proj) and the component orthogonal to the subspace (norm), such that:
self = proj + norm
The projection is computed using the least squares solution.
Parameters:
-
to(Matrix) –The matrix whose columns form the subspace onto which to project
self. -
verbosity(int, default:0) –Level of verbosity for displaying intermediate results.
- 0: No output.
- 1: Display the projected and normal components.
- 2: Display detailed steps.
Returns:
Examples:
| Python Console Session | |
|---|---|
Source code in src/ma1522/symbolic.py
proj_comp(to: Matrix, verbosity: int = 0) -> Matrix
¶
Computes the orthogonal projection of the current vector (or matrix) onto the subspace spanned by the columns of another matrix.
This method returns the component of self that lies in the subspace defined by the columns of to.
It is equivalent to the projection of self onto the subspace, as computed by the orthogonal decomposition.
Parameters:
-
to(Matrix) –The matrix whose columns form the subspace onto which to project
self. -
verbosity(int, default:0) –Level of verbosity for displaying intermediate results.
- 0: No output.
- 1: Display the projected component.
Returns:
-
Matrix–The projection of
selfonto the subspace spanned byto.
Examples:
| Python Console Session | |
|---|---|
Source code in src/ma1522/symbolic.py
norm_comp(to: Matrix, verbosity: int = 0) -> Matrix
¶
Computes the component of the current vector (or matrix) orthogonal to the subspace spanned by the columns of another matrix.
This method returns the part of self that is perpendicular to the subspace defined by the columns of to.
It is equivalent to the normal component from the orthogonal decomposition.
Parameters:
-
to(Matrix) –The matrix whose columns form the subspace to which the orthogonal component is computed.
-
verbosity(int, default:0) –Level of verbosity for displaying intermediate results.
- 0: No output (default).
- 1: Display the normal component.
Returns:
-
Matrix–The component of
selforthogonal to the subspace spanned byto.
Examples:
| Python Console Session | |
|---|---|
Source code in src/ma1522/symbolic.py
gram_schmidt(factor: bool = True, verbosity: int = 1) -> Matrix | ScalarFactor
¶
Performs Gram-Schmidt orthogonalization to convert a set of vectors (columns of the matrix) into an orthogonal set (that includes 0 vectors if any).
Parameters:
-
factor(bool, default:True) –If
True, the resulting orthogonal vectors will be scaled to have integer factors. -
verbosity(int, default:1) –Level of verbosity:
- 0: No output.
- 1: Display intermediate results for each step of the process.
Returns:
-
Matrix–A matrix whose columns are the orthogonalized vectors.
Examples:
| Python Console Session | |
|---|---|
Source code in src/ma1522/symbolic.py
QRdecomposition(full: bool = False, verbosity: int = 0) -> QR
¶
Computes the QR decomposition of the matrix. Optionally computes the full QR decomposition.
A full QR decomposition returns an orthogonal (square) matrix Q and an upper triangular matrix R
such that self = Q @ R. On the other hand, a reduced QR decomposition returns Q and R such that
self = Q @ R, where Q has orthonormal columns.
Parameters:
-
full(bool, default:False) –If
True, computes the full QR decomposition. -
verbosity(int, default:0) –Level of verbosity for displaying intermediate results:
- 0: No output.
- 1: Display intermediate results for each step of the process.
Returns:
-
QR–
Examples:
| Python Console Session | |
|---|---|
See Also
- SymPy's
Matrix.QRdecomposition gram_schmidtfor performing the Gram-Schmidt process to find an orthogonal basis.
Source code in src/ma1522/symbolic.py
solve_least_squares(rhs: Matrix, verbosity: int = 1, matrices: int = 1, *args, **kwargs) -> Matrix | PartGen
¶
Solves the least squares problem \(\min || \mathrm{self} \, \mathbf{x} - \mathrm{rhs}||^2\).
Uses SymPy's built-in method for least squares when the rank condition is met, otherwise uses a custom solution approach using the normal equations: \(\mathrm{self}^{\top} \mathrm{self} \, \mathbf{x} = \mathrm{self}^{\top} \mathrm{rhs}\)
Parameters:
-
rhs(Matrix) –The right-hand side matrix/vector
binAx = b. -
verbosity(int, default:1) –Level of verbosity (default is
1):- 0: No output.
- 1: Display intermediate steps.
-
matrices(int, default:1) –- 1: Returns the least squares solution matrix.
- 2: Returns a
PartGenwith the part solution and general solution.
-
*args–Additional positional arguments passed to SymPy's
solve_least_squaresmethod. -
**kwargs–Additional arguments passed to to SymPy's
solve_least_squaresmethod.
Returns:
-
Matrix–If
matrices=1, returns the least squares solution matrix. -
PartGen–If
matrices=2, returns aPartGenwith the part solution and general solution.
Examples:
Source code in src/ma1522/symbolic.py
| Python | |
|---|---|
3554 3555 3556 3557 3558 3559 3560 3561 3562 3563 3564 3565 3566 3567 3568 3569 3570 3571 3572 3573 3574 3575 3576 3577 3578 3579 3580 3581 3582 3583 3584 3585 3586 3587 3588 3589 3590 3591 3592 3593 3594 3595 3596 3597 3598 3599 3600 3601 3602 3603 3604 3605 3606 3607 3608 3609 3610 3611 3612 3613 3614 3615 3616 3617 3618 3619 3620 3621 3622 3623 3624 3625 3626 3627 3628 | |
create_vander(num_rows: int = 1, num_cols: int = 1, symbol: str = 'x', is_real: bool = True) -> Matrix
staticmethod
¶
Creates a Vandermonde matrix with symbolic entries.
This method generates a Vandermonde matrix of size num_rows x num_cols
where the entries are symbolic expressions. Each row in the matrix is formed
by raising a symbolic variable (indexed by row) to increasing powers (from 0
to num_cols-1). The is_real flag determines whether the symbols are real-valued.
Parameters:
-
num_rows(int, default:1) –The number of rows in the Vandermonde matrix.
-
num_cols(int, default:1) –The number of columns in the Vandermonde matrix.
-
symbol(str, default:'x') –The base name for the symbols used in the matrix entries.
-
is_real(bool, default:True) –If True (default), the symbols are real-valued; otherwise, they are complex.
Returns:
-
Matrix–A Vandermonde matrix with symbolic entries.
Examples:
| Python Console Session | |
|---|---|
See Also
apply_vanderfor applying the Vandermonde transformation to a matrix.
Source code in src/ma1522/symbolic.py
apply_vander(x: Matrix) -> Matrix
¶
Applies a Vandermonde transformation to the current matrix using the given vector.
This method applies a Vandermonde transformation to the current matrix by
substituting the free symbols in the last column with corresponding values
from the provided vector x. The number of rows in self must match the
number of elements in x, and x must be a column vector.
Note
- The matrix
selfis expected to be created viaMatrix.create_vander(). - The
xvector provides the values to substitute in place of these symbols.
Parameters:
-
x(Matrix) –A column vector (Matrix object with a single column) containing the values to substitute into the last column of the matrix.
Returns:
-
Matrix–A new Matrix object where the free symbols in the last column of the original matrix are substituted by the corresponding values from
x.
Raises:
-
ShapeError–If
xis not a column vector or if the number of rows inselfdoes not match the size ofx.
Examples:
| Python Console Session | |
|---|---|
Source code in src/ma1522/symbolic.py
cpoly(force_factor: bool = True) -> Mul | tuple[Mul, Mul]
¶
Computes the characteristic polynomial of the matrix and attempts to factor it into real and complex parts.
The characteristic polynomial is defined as det(x * I - self), where I is the identity matrix of the same size as self.
Parameters:
-
force_factor(bool, default:True) –If
True, the polynomial is fully factored, even if it doesn't have real factors. IfFalse, the polynomial is returned in its factored form if possible.
Returns:
-
Mul–If the polynomial factors only into real terms, returns a single factored polynomial.
-
tuple[Mul, Mul]–If the polynomial has both real and complex factors, returns a tuple of two polynomials one with real factors and the other with complex factors.
Examples:
Source code in src/ma1522/symbolic.py
is_diagonalizable(reals_only: bool = True, verbosity: int = 1, *args, **kwargs) -> bool
¶
Checks if the matrix is diagonalizable, with the option to focus only on real eigenvalues.
A matrix is diagonalizable if it has enough linearly independent eigenvectors to form a basis for the space.
Parameters:
-
reals_only(bool, default:True) –If True, diagonalization will focus on real eigenvalues.
-
verbosity(int, default:1) –Controls the level of output during the diagonalization process.
- 0: No output.
- 1: Displays the characteristic polynomial, eigenvalues, algebraic multiplicities, and eigenspaces.
-
*args–Additional positional arguments passed to SymPy's
is_diagonalizablemethod. -
**kwargs–Additional arguments passed to SymPy's
is_diagonalizablemethod.
Returns:
-
bool–True if the matrix is diagonalizable, False otherwise.
Examples:
| Python Console Session | |
|---|---|
See Also
- SymPy's
Matrix.is_diagonalizable - Sympy's
Matrix.eigenvectsfor computing eigenvalues and their multiplicities. diagonalizefor diagonalizing the matrix.
Source code in src/ma1522/symbolic.py
eigenvects_associated(eigenvalue: Expr | int | float) -> list[Matrix] | None
¶
Computes the eigenvectors associated with a given eigenvalue.
This method finds all (nonzero) vectors v such that (eigenvalue * I - self) * v = 0
where I is the identity matrix of the same size as self.
Parameters:
Returns:
-
list[Matrix]–A list of eigenvectors (as Matrix objects) associated with the given eigenvalue,
-
None–If the eigenvalue does not correspond to any eigenvectors.
Examples:
| Python Console Session | |
|---|---|
Source code in src/ma1522/symbolic.py
diagonalize(reals_only: bool = True, verbosity: int = 0, *args, **kwargs) -> PDP
¶
Diagonalizes the matrix if possible, focusing on real eigenvalues unless specified otherwise.
Parameters:
-
reals_only(bool, default:True) –If
True, diagonalization will focus on real eigenvalues. -
verbosity(int, default:0) –Controls the level of output during the diagonalization process.
- 0: No output.
- 1: Displays the characteristic polynomial and eigenvectors.
-
*args–Additional positional arguments passed to SymPy's
diagonalizemethod. -
**kwargs–Additional arguments passed to SymPy's
diagonalizemethod.
Returns:
-
PDP–
Raises:
-
MatrixError–If the matrix is not diagonalizable.
Examples:
| Python Console Session | |
|---|---|
Source code in src/ma1522/symbolic.py
| Python | |
|---|---|
3851 3852 3853 3854 3855 3856 3857 3858 3859 3860 3861 3862 3863 3864 3865 3866 3867 3868 3869 3870 3871 3872 3873 3874 3875 3876 3877 3878 3879 3880 3881 3882 3883 3884 3885 3886 3887 3888 3889 3890 3891 3892 3893 3894 3895 3896 3897 3898 3899 3900 3901 3902 3903 3904 3905 3906 3907 3908 3909 3910 3911 3912 3913 | |
is_orthogonally_diagonalizable(verbosity: int = 2) -> bool
¶
Determines whether the matrix is orthogonally diagonalizable.
A matrix is orthogonally diagonalizable if and only if it is symmetric. This method checks the symmetry of the matrix and optionally displays diagnostic information based on the verbosity level.
Parameters:
-
verbosity(int, default:2) –Level of diagnostic output.
- 0: No output.
- 1: Displays the matrix.
- 2: Displays the result of the symmetry check.
Returns:
-
bool–True if the matrix is symmetric (orthogonally diagonalizable), False otherwise.
Examples:
| Python Console Session | |
|---|---|
See Also
- SymPy's
Matrix.is_symmetric
Source code in src/ma1522/symbolic.py
orthogonally_diagonalize(reals_only: bool = True, factor: bool = True, verbosity=1, *args, **kwargs) -> PDP
¶
Orthogonally diagonalizes the matrix, ensuring that eigenvectors corresponding to different eigenvalues are orthogonal.
Parameters:
-
reals_only(bool, default:True) –If True, only real eigenvalues are considered.
-
factor(bool, default:True) –If True, the eigenvectors are orthogonalized using the Gram-Schmidt process.
-
verbosity(int, default:1) –Controls the verbosity of output during the process.
-
*args–Additional positional arguments passed to the
diagonalizemethod. -
**kwargs–Additional arguments passed to the
diagonalizemethod.
Returns:
-
PDP–
Raises:
-
AssertionError–If the matrix is not orthogonally diagonalizable (i.e., not symmetric).
Examples:
| Python Console Session | |
|---|---|
See Also
is_orthogonally_diagonalizableto check if the matrix is orthogonally diagonalizable.diagonalizefor diagonalizing the matrix.
Source code in src/ma1522/symbolic.py
| Python | |
|---|---|
3949 3950 3951 3952 3953 3954 3955 3956 3957 3958 3959 3960 3961 3962 3963 3964 3965 3966 3967 3968 3969 3970 3971 3972 3973 3974 3975 3976 3977 3978 3979 3980 3981 3982 3983 3984 3985 3986 3987 3988 3989 3990 3991 3992 3993 3994 3995 3996 3997 3998 3999 4000 4001 4002 4003 4004 4005 4006 4007 4008 4009 4010 4011 4012 4013 4014 4015 4016 4017 4018 4019 4020 4021 4022 4023 4024 4025 4026 4027 4028 4029 4030 4031 4032 4033 | |
is_stochastic(verbosity: int = 1) -> bool
¶
Checks if the matrix is stochastic.
A matrix is stochastic if all its entries are non-negative and each column sums to 1. This property is commonly used to identify transition matrices in Markov chains.
Parameters:
-
verbosity(int, default:1) –Level of diagnostic output.
- 0: No output.
- 1: Displays the result of the checks.
Returns:
-
bool–True if the matrix is stochastic, False otherwise.
Examples:
| Python Console Session | |
|---|---|
| Python Console Session | |
|---|---|
Source code in src/ma1522/symbolic.py
equilibrium_vectors() -> Matrix
¶
Computes the equilibrium vectors of the matrix, i.e., the nullspace of (I - A).
Note
- A matrix
Phas a unique equilibrium vector if it is stochastic and there exists some positive integerksuch thatP^konly has positive entries.
Returns:
-
Matrix–A matrix containing equilibrium vectors normalized so that their column sums to 1.
Examples:
| Python Console Session | |
|---|---|
Source code in src/ma1522/symbolic.py
singular_value_decomposition(verbosity: int = 0, tol: float = 0.0, verify: bool = True) -> SVD
¶
Performs Singular Value Decomposition (SVD) on the matrix, following the MA1522 syllabus.
Note
- This function is known to take too much time and may kill Jupyter's kernel. Please use it with caution.
A workaround is to set
verify=Falseto skip the verification step, or use the faster numerical SVD methodfast_svdinstead.
Parameters:
-
verbosity(int, default:0) –Controls the verbosity of the output.
- 0: No output.
- 1: Displays intermediate steps and results of the SVD process.
-
tol(float, default:0.0) –Tolerance for verification of the SVD result.
-
verify(bool, default:True) –If
True, verifies the result of the SVD by checking ifself = U @ S @ V.T. IfFalse, skips the verification step for performance reasons.
Returns:
-
SVD–
Examples:
See Also
fast_svdfor a faster numerical SVD- SymPy's
Matrix.singular_value_decomposition
Source code in src/ma1522/symbolic.py
| Python | |
|---|---|
4096 4097 4098 4099 4100 4101 4102 4103 4104 4105 4106 4107 4108 4109 4110 4111 4112 4113 4114 4115 4116 4117 4118 4119 4120 4121 4122 4123 4124 4125 4126 4127 4128 4129 4130 4131 4132 4133 4134 4135 4136 4137 4138 4139 4140 4141 4142 4143 4144 4145 4146 4147 4148 4149 4150 4151 4152 4153 4154 4155 4156 4157 4158 4159 4160 4161 4162 4163 4164 4165 4166 4167 4168 4169 4170 4171 4172 4173 4174 4175 4176 4177 4178 4179 4180 4181 4182 4183 4184 4185 4186 4187 4188 4189 4190 4191 4192 4193 4194 4195 4196 4197 4198 4199 4200 4201 4202 4203 4204 4205 4206 4207 4208 4209 4210 4211 4212 4213 4214 4215 4216 4217 4218 4219 4220 4221 4222 4223 4224 4225 | |
fast_svd(option: Literal['np', 'sym'] = 'np', identify: bool = True, tol: float | None = None) -> SVD | NumSVD
¶
A faster version of SVD that computes numerically using NumPy's SVD function.
This method is designed to be efficient and suitable for large matrices, but it does not guarantee
exact symbolic results like the singular_value_decomposition method.
It uses numpy.linalg.svd function to compute the singular value decomposition and
mpmath.identify function to identify rational numbers or surds if requested.
Note
- This method might not return exact values, even if identification is enabled as it does not use SymPy's symbolic computation for SVD.
- Use this method when performance is a concern and exact symbolic results are not required.
Parameters:
-
option(Literal['np', 'sym'], default:'np') –Whether to return numpy arrays or sympy matrices.
-
identify(bool, default:True) –Whether to attempt identification of rational numbers or surds. If
True,optionmust be"sym"to return symbolic matrices. -
tol(float, default:None) –Tolerance for
mpmath.identifyfunction as well as for verifying the SVD result.
Returns:
-
SVD– -
NumSVD–A named tuple containing:
U(numpy.ndarray): The left singular vectors as a NumPy array.S(numpy.ndarray): The diagonal matrix of singular values as a NumPy array.V(numpy.ndarray): The right singular vectors as a NumPy array.
Examples:
See Also
singular_value_decompositionfor the symbolic version of SVD.- NumPy's
numpy.linalg.svdfor the underlying numerical SVD implementation.
Source code in src/ma1522/symbolic.py
| Python | |
|---|---|
4227 4228 4229 4230 4231 4232 4233 4234 4235 4236 4237 4238 4239 4240 4241 4242 4243 4244 4245 4246 4247 4248 4249 4250 4251 4252 4253 4254 4255 4256 4257 4258 4259 4260 4261 4262 4263 4264 4265 4266 4267 4268 4269 4270 4271 4272 4273 4274 4275 4276 4277 4278 4279 4280 4281 4282 4283 4284 4285 4286 4287 4288 4289 4290 4291 4292 4293 4294 4295 4296 4297 4298 4299 4300 4301 4302 4303 4304 4305 4306 4307 4308 4309 4310 4311 4312 4313 4314 4315 4316 4317 4318 4319 4320 4321 4322 4323 | |
standard_matrix(out: Matrix, matrices: int = 1) -> list[Matrix] | list[PartGen]
¶
Returns the standard matrix for the transformation from self to out.
The standard matrix is a matrix T such that T @ self = out, where self is the matrix
whos columns represent the input vectors and out is the matrix whose columns represent the output vectors.
Note
- The standard matrix may not be unique if the transformation is not injective.
- If multiple solutions are found, the first solution is returned.
Parameters:
-
out(Matrix) –The target matrix for the transformation.
-
matrices(int, default:1) –The type of matrices to return:
- 1: Returns the standard matrix.
- 2: Returns a
PartGenwith the part solution and general solution.
Returns:
-
list[Matrix]–If
matrices=1, returns the standard matrix for the transformation. -
list[PartGen]–If
matrices=2, returns aPartGenwith the part solution and general solution.
Examples:
| Python Console Session | |
|---|---|
Source code in src/ma1522/symbolic.py
| Python | |
|---|---|
4329 4330 4331 4332 4333 4334 4335 4336 4337 4338 4339 4340 4341 4342 4343 4344 4345 4346 4347 4348 4349 4350 4351 4352 4353 4354 4355 4356 4357 4358 4359 4360 4361 4362 4363 4364 4365 4366 4367 4368 4369 4370 4371 4372 4373 4374 4375 4376 4377 4378 4379 4380 4381 4382 4383 4384 4385 4386 4387 4388 4389 4390 4391 4392 4393 4394 4395 4396 4397 4398 | |