Skip to content

Inherited Methods Summary

This page summarizes the methods and attributes that the custom Matrix class inherits from the sympy.MutableDenseMatrix class. These inherited methods and attributes are essential for performing various matrix operations and manipulations.

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
1
2
3
4
5
6
>>> A = Matrix([[1, 2], [3, 4]])
>>> A.rref()
RREF(rref=Matrix([
[1, 0]
[0, 1]
]), pivots=(0, 1))

Creating from LaTeX:

Python Console Session
1
2
3
4
>>> B = Matrix.from_latex(r'\begin{pmatrix} 1 & 2 \\ 3 & 4 \end{pmatrix}')
⎡1  2⎤
⎢    ⎥
⎣3  4⎦

Eigenvalue decomposition:

Python Console Session
1
2
3
4
5
6
7
8
9
>>> P, D = A.diagonalize(verbosity=0)
>>> P, D
(Matrix([
[-sqrt(33)/6 - 1/2, -1/2 + sqrt(33)/6]
[                1,                 1]
]), Matrix([
[5/2 - sqrt(33)/2,                0]
[               0, 5/2 + sqrt(33)/2]
]))

Methods:

__slots__ = () class-attribute instance-attribute

_repr_png_ = _repr_disabled class-attribute instance-attribute

_repr_svg_ = _repr_disabled class-attribute instance-attribute

_op_priority = 10.01 class-attribute instance-attribute

__array_priority__ = 11 class-attribute instance-attribute

is_Matrix = True class-attribute instance-attribute

_class_priority = 4 class-attribute instance-attribute

_sympify = staticmethod(sympify) class-attribute instance-attribute

zero = S.Zero class-attribute instance-attribute

one = S.One class-attribute instance-attribute

_diff_wrt = True class-attribute instance-attribute

rows = None class-attribute instance-attribute

cols = None class-attribute instance-attribute

_simplify = None class-attribute instance-attribute

shape property

The shape (dimensions) of the matrix as the 2-tuple (rows, cols).

Examples

from sympy import zeros M = zeros(2, 3) M.shape (2, 3) M.rows 2 M.cols 3

free_symbols property

Returns the free symbols within the matrix.

Examples

from sympy.abc import x from sympy import Matrix Matrix([[x], [1]]).free_symbols

is_weakly_diagonally_dominant property

Tests if the matrix is row weakly diagonally dominant.

Explanation

A \(n, n\) matrix \(A\) is row weakly diagonally dominant if

.. math:: \left|A_{i, i}\right| \ge \sum_{j = 0, j \neq i}^{n-1} \left|A_{i, j}\right| \quad {\text{for all }} i \in { 0, ..., n-1 }

Examples

from sympy import Matrix A = Matrix([[3, -2, 1], [1, -3, 2], [-1, 2, 4]]) A.is_weakly_diagonally_dominant True

A = Matrix([[-2, 2, 1], [1, 3, 2], [1, -2, 0]]) A.is_weakly_diagonally_dominant False

A = Matrix([[-4, 2, 1], [1, 6, 2], [1, -2, 5]]) A.is_weakly_diagonally_dominant True

Notes

If you want to test whether a matrix is column diagonally dominant, you can apply the test after transposing the matrix.

is_strongly_diagonally_dominant property

Tests if the matrix is row strongly diagonally dominant.

Explanation

A \(n, n\) matrix \(A\) is row strongly diagonally dominant if

.. math:: \left|A_{i, i}\right| > \sum_{j = 0, j \neq i}^{n-1} \left|A_{i, j}\right| \quad {\text{for all }} i \in { 0, ..., n-1 }

Examples

from sympy import Matrix A = Matrix([[3, -2, 1], [1, -3, 2], [-1, 2, 4]]) A.is_strongly_diagonally_dominant False

A = Matrix([[-2, 2, 1], [1, 3, 2], [1, -2, 0]]) A.is_strongly_diagonally_dominant False

A = Matrix([[-4, 2, 1], [1, 6, 2], [1, -2, 5]]) A.is_strongly_diagonally_dominant True

Notes

If you want to test whether a matrix is column diagonally dominant, you can apply the test after transposing the matrix.

is_hermitian property

Checks if the matrix is Hermitian.

In a Hermitian matrix element i,j is the complex conjugate of element j,i.

Examples

from sympy import Matrix from sympy import I from sympy.abc import x a = Matrix([[1, I], [-I, 1]]) a Matrix([ [ 1, I], [-I, 1]]) a.is_hermitian True a[0, 0] = 2I a.is_hermitian False a[0, 0] = x a.is_hermitian a[0, 1] = a[1, 0]I a.is_hermitian False

is_Identity: FuzzyBool property

is_lower_hessenberg property

Checks if the matrix is in the lower-Hessenberg form.

The lower hessenberg matrix has zero entries above the first superdiagonal.

Examples

from sympy import Matrix a = Matrix([[1, 2, 0, 0], [5, 2, 3, 0], [3, 4, 3, 7], [5, 6, 1, 1]]) a Matrix([ [1, 2, 0, 0], [5, 2, 3, 0], [3, 4, 3, 7], [5, 6, 1, 1]]) a.is_lower_hessenberg True

See Also

is_upper_hessenberg is_lower

is_lower property

Check if matrix is a lower triangular matrix. True can be returned even if the matrix is not square.

Examples

from sympy import Matrix m = Matrix(2, 2, [1, 0, 0, 1]) m Matrix([ [1, 0], [0, 1]]) m.is_lower True

m = Matrix(4, 3, [0, 0, 0, 2, 0, 0, 1, 4, 0, 6, 6, 5]) m Matrix([ [0, 0, 0], [2, 0, 0], [1, 4, 0], [6, 6, 5]]) m.is_lower True

from sympy.abc import x, y m = Matrix(2, 2, [x2 + y, y2 + x, 0, x + y]) m Matrix([ [x2 + y, x + y2], [ 0, x + y]]) m.is_lower False

See Also

is_upper is_diagonal is_lower_hessenberg

is_square property

Checks if a matrix is square.

A matrix is square if the number of rows equals the number of columns. The empty matrix is square by definition, since the number of rows and the number of columns are both zero.

Examples

from sympy import Matrix a = Matrix([[1, 2, 3], [4, 5, 6]]) b = Matrix([[1, 2, 3], [4, 5, 6], [7, 8, 9]]) c = Matrix([]) a.is_square False b.is_square True c.is_square True

is_upper_hessenberg property

Checks if the matrix is the upper-Hessenberg form.

The upper hessenberg matrix has zero entries below the first subdiagonal.

Examples

from sympy import Matrix a = Matrix([[1, 4, 2, 3], [3, 4, 1, 7], [0, 2, 3, 4], [0, 0, 1, 3]]) a Matrix([ [1, 4, 2, 3], [3, 4, 1, 7], [0, 2, 3, 4], [0, 0, 1, 3]]) a.is_upper_hessenberg True

See Also

is_lower_hessenberg is_upper

is_upper property

Check if matrix is an upper triangular matrix. True can be returned even if the matrix is not square.

Examples

from sympy import Matrix m = Matrix(2, 2, [1, 0, 0, 1]) m Matrix([ [1, 0], [0, 1]]) m.is_upper True

m = Matrix(4, 3, [5, 1, 9, 0, 4, 6, 0, 0, 5, 0, 0, 0]) m Matrix([ [5, 1, 9], [0, 4, 6], [0, 0, 5], [0, 0, 0]]) m.is_upper True

m = Matrix(2, 3, [4, 2, 5, 6, 1, 1]) m Matrix([ [4, 2, 5], [6, 1, 1]]) m.is_upper False

See Also

is_lower is_diagonal is_upper_hessenberg

is_zero_matrix property

Checks if a matrix is a zero matrix.

A matrix is zero if every element is zero. A matrix need not be square to be considered zero. The empty matrix is zero by the principle of vacuous truth. For a matrix that may or may not be zero (e.g. contains a symbol), this will be None

Examples

from sympy import Matrix, zeros from sympy.abc import x a = Matrix([[0, 0], [0, 0]]) b = zeros(3, 4) c = Matrix([[0, 1], [0, 0]]) d = Matrix([]) e = Matrix([[x, 0], [0, 0]]) a.is_zero_matrix True b.is_zero_matrix True c.is_zero_matrix False d.is_zero_matrix True e.is_zero_matrix

H property

Return Hermite conjugate.

Examples

from sympy import Matrix, I m = Matrix((0, 1 + I, 2, 3)) m Matrix([ [ 0], [1 + I], [ 2], [ 3]]) m.H Matrix([[0, 1 - I, 2, 3]])

See Also

conjugate: By-element conjugation sympy.matrices.matrixbase.MatrixBase.D: Dirac conjugation

C property

By-element conjugation

is_echelon property

orthogonalize = classmethod(orthogonalize) class-attribute instance-attribute

is_positive_definite property

is_positive_semidefinite property

is_negative_definite property

is_negative_semidefinite property

is_indefinite property

kind: MatrixKind property

D property

Return Dirac conjugate (if self.rows == 4).

Examples

from sympy import Matrix, I, eye m = Matrix((0, 1 + I, 2, 3)) m.D Matrix([[0, 1 - I, -2, -3]]) m = (eye(4) + I*eye(4)) m[0, 3] = 2 m.D Matrix([ [1 - I, 0, 0, 0], [ 0, 1 - I, 0, 0], [ 0, 0, -1 + I, 0], [ 2, 0, 0, -1 + I]])

If the matrix does not have 4 rows an AttributeError will be raised because this property is only defined for matrices with 4 rows.

Matrix(eye(2)).D Traceback (most recent call last): ... AttributeError: Matrix has no attribute D.

See Also

sympy.matrices.matrixbase.MatrixBase.conjugate: By-element conjugation sympy.matrices.matrixbase.MatrixBase.H: Hermite conjugation

_sage_ = Basic._sage_ class-attribute instance-attribute

_rep: DomainMatrix instance-attribute

is_zero = False class-attribute instance-attribute

is_MatrixExpr = False class-attribute instance-attribute

_mat property

_repr_disabled()

No-op repr function used to disable jupyter display hooks.

When :func:sympy.init_printing is used to disable certain display formats, this function is copied into the appropriate _repr_*_ attributes.

While we could just set the attributes to None``, doing it this way allows derived classes to callsuper()`.

_repr_latex_()

IPython/Jupyter LaTeX printing

To change the behavior of this (e.g., pass in some settings to LaTeX), use init_printing(). init_printing() will also enable LaTeX printing for built in numeric types like ints and container types that contain SymPy objects, like lists and dictionaries of expressions.

_new(*args, copy=True, **kwargs) classmethod

__getitem__(key)

_eval_col_del(col)

_eval_col_insert(col, other)

_eval_col_join(other)

_eval_extract(rowsList, colsList)

_eval_get_diag_blocks()

_eval_row_del(row)

_eval_row_insert(row, other)

_eval_row_join(other)

_eval_tolist()

_eval_todok()

_eval_from_dok(rows, cols, dok) classmethod

_eval_vec()

_eval_vech(diagonal)

col_del(col)

Delete the specified column.

col_insert(pos, other)

Insert one or more columns at the given column position.

Examples

from sympy import zeros, ones M = zeros(3) V = ones(3, 1) M.col_insert(1, V) Matrix([ [0, 1, 0, 0], [0, 1, 0, 0], [0, 1, 0, 0]])

See Also

col row_insert

col(j)

Elementary column selector.

Examples

from sympy import eye eye(2).col(0) Matrix([ [1], [0]])

See Also

row col_del col_join col_insert

extract(rowsList, colsList)

Return a submatrix by specifying a list of rows and columns. Negative indices can be given. All indices must be in the range \(-n \le i < n\) where \(n\) is the number of rows or columns.

Examples

from sympy import Matrix m = Matrix(4, 3, range(12)) m Matrix([ [0, 1, 2], [3, 4, 5], [6, 7, 8], [9, 10, 11]]) m.extract([0, 1, 3], [0, 1]) Matrix([ [0, 1], [3, 4], [9, 10]])

Rows or columns can be repeated:

m.extract([0, 0, 1], [-1]) Matrix([ [2], [2], [5]])

Every other row can be taken by using range to provide the indices:

m.extract(range(0, m.rows, 2), [-1]) Matrix([ [2], [8]])

RowsList or colsList can also be a list of booleans, in which case the rows or columns corresponding to the True values will be selected:

m.extract([0, 1, 2, 3], [True, False, True]) Matrix([ [0, 2], [3, 5], [6, 8], [9, 11]])

get_diag_blocks()

Obtains the square sub-matrices on the main diagonal of a square matrix.

Useful for inverting symbolic matrices or solving systems of linear equations which may be decoupled by having a block diagonal structure.

Examples

from sympy import Matrix from sympy.abc import x, y, z A = Matrix([[1, 3, 0, 0], [y, zz, 0, 0], [0, 0, x, 0], [0, 0, 0, 0]]) a1, a2, a3 = A.get_diag_blocks() a1 Matrix([ [1, 3], [y, z*2]]) a2 Matrix([[x]]) a3 Matrix([[0]])

hstack(*args) classmethod

Return a matrix formed by joining args horizontally (i.e. by repeated application of row_join).

Examples

from sympy import Matrix, eye Matrix.hstack(eye(2), 2*eye(2)) Matrix([ [1, 0, 2, 0], [0, 1, 0, 2]])

reshape(rows, cols)

Reshape the matrix. Total number of elements must remain the same.

Examples

from sympy import Matrix m = Matrix(2, 3, lambda i, j: 1) m Matrix([ [1, 1, 1], [1, 1, 1]]) m.reshape(1, 6) Matrix([[1, 1, 1, 1, 1, 1]]) m.reshape(3, 2) Matrix([ [1, 1], [1, 1], [1, 1]])

row_del(row)

Delete the specified row.

row_insert(pos, other)

Insert one or more rows at the given row position.

Examples

from sympy import zeros, ones M = zeros(3) V = ones(1, 3) M.row_insert(1, V) Matrix([ [0, 0, 0], [1, 1, 1], [0, 0, 0], [0, 0, 0]])

See Also

row col_insert

diagonal(k=0)

Returns the kth diagonal of self. The main diagonal corresponds to k=0; diagonals above and below correspond to k > 0 and k < 0, respectively. The values of self[i, j] for which j - i = k, are returned in order of increasing i + j, starting with i + j = |k|.

Examples

from sympy import Matrix m = Matrix(3, 3, lambda i, j: j - i); m Matrix([ [ 0, 1, 2], [-1, 0, 1], [-2, -1, 0]]) _.diagonal() Matrix([[0, 0, 0]]) m.diagonal(1) Matrix([[1, 1]]) m.diagonal(-2) Matrix([[-2]])

Even though the diagonal is returned as a Matrix, the element retrieval can be done with a single index:

Matrix.diag(1, 2, 3).diagonal()[1] # instead of [0, 1] 2

See Also

diag

row(i)

Elementary row selector.

Examples

from sympy import eye eye(2).row(0) Matrix([[1, 0]])

See Also

col row_del row_join row_insert

todok()

Return the matrix as dictionary of keys.

Examples

from sympy import Matrix M = Matrix.eye(3) M.todok()

from_dok(rows, cols, dok) classmethod

Create a matrix from a dictionary of keys.

Examples

from sympy import Matrix d = {(0, 0): 1, (1, 2): 3, (2, 1): 4} Matrix.from_dok(3, 3, d) Matrix([ [1, 0, 0], [0, 0, 3], [0, 4, 0]])

tolist()

Return the Matrix as a nested Python list.

Examples

from sympy import Matrix, ones m = Matrix(3, 3, range(9)) m Matrix([ [0, 1, 2], [3, 4, 5], [6, 7, 8]]) m.tolist() [[0, 1, 2], [3, 4, 5], [6, 7, 8]] ones(3, 0).tolist() [[], [], []]

When there are no rows then it will not be possible to tell how many columns were in the original matrix:

ones(0, 3).tolist() []

todod(M)

Returns matrix as dict of dicts containing non-zero elements of the Matrix

Examples

from sympy import Matrix A = Matrix([[0, 1],[0, 3]]) A Matrix([ [0, 1], [0, 3]]) A.todod() {0: {1: 1}, 1: {1: 3}}

vec()

Return the Matrix converted into a one column matrix by stacking columns

Examples

from sympy import Matrix m=Matrix([[1, 3], [2, 4]]) m Matrix([ [1, 3], [2, 4]]) m.vec() Matrix([ [1], [2], [3], [4]])

See Also

vech

vech(diagonal=True, check_symmetry=True)

Reshapes the matrix into a column vector by stacking the elements in the lower triangle.

Parameters

bool, optional

If True, it includes the diagonal elements.

bool, optional

If True, it checks whether the matrix is symmetric.

Examples

from sympy import Matrix m=Matrix([[1, 2], [2, 3]]) m Matrix([ [1, 2], [2, 3]]) m.vech() Matrix([ [1], [2], [3]]) m.vech(diagonal=False) Matrix([[2]])

Notes

This should work for symmetric matrices and vech can represent symmetric matrices in vector form with less size than vec.

See Also

vec

vstack(*args) classmethod

Return a matrix formed by joining args vertically (i.e. by repeated application of col_join).

Examples

from sympy import Matrix, eye Matrix.vstack(eye(2), 2*eye(2)) Matrix([ [1, 0], [0, 1], [2, 0], [0, 2]])

_eval_diag(rows, cols, diag_dict) classmethod

diag_dict is a defaultdict containing all the entries of the diagonal matrix.

_eval_eye(rows, cols) classmethod

_eval_jordan_block(size: int, eigenvalue, band='upper') classmethod

_eval_ones(rows, cols) classmethod

_eval_zeros(rows, cols) classmethod

_eval_wilkinson(n) classmethod

jordan_block(kls, size=None, eigenvalue=None, *, band='upper', **kwargs) classmethod

Returns a Jordan block

Parameters

Integer, optional

Specifies the shape of the Jordan block matrix.

Number or Symbol

Specifies the value for the main diagonal of the matrix.

.. note:: The keyword eigenval is also specified as an alias of this keyword, but it is not recommended to use.

Text Only
1
We may deprecate the alias in later release.
'upper' or 'lower', optional

Specifies the position of the off-diagonal to put 1 s on.

Matrix, optional

Specifies the matrix class of the output form.

If it is not specified, the class type where the method is being executed on will be returned.

Returns

Matrix A Jordan block matrix.

Raises

ValueError If insufficient arguments are given for matrix size specification, or no eigenvalue is given.

Examples

Creating a default Jordan block:

from sympy import Matrix from sympy.abc import x Matrix.jordan_block(4, x) Matrix([ [x, 1, 0, 0], [0, x, 1, 0], [0, 0, x, 1], [0, 0, 0, x]])

Creating an alternative Jordan block matrix where 1 is on lower off-diagonal:

Matrix.jordan_block(4, x, band='lower') Matrix([ [x, 0, 0, 0], [1, x, 0, 0], [0, 1, x, 0], [0, 0, 1, x]])

Creating a Jordan block with keyword arguments

Matrix.jordan_block(size=4, eigenvalue=x) Matrix([ [x, 1, 0, 0], [0, x, 1, 0], [0, 0, x, 1], [0, 0, 0, x]])

References

.. [1] https://en.wikipedia.org/wiki/Jordan_matrix

companion(kls, poly) classmethod

Returns a companion matrix of a polynomial.

Examples

from sympy import Matrix, Poly, Symbol, symbols x = Symbol('x') c0, c1, c2, c3, c4 = symbols('c0:5') p = Poly(c0 + c1x + c2x2 + c3*x3 + c4x4 + x*5, x) Matrix.companion(p) Matrix([ [0, 0, 0, 0, -c0], [1, 0, 0, 0, -c1], [0, 1, 0, 0, -c2], [0, 0, 1, 0, -c3], [0, 0, 0, 1, -c4]])

wilkinson(kls, n, **kwargs) classmethod

Returns two square Wilkinson Matrix of size 2*n + 1 \(W_{2n + 1}^-, W_{2n + 1}^+ =\) Wilkinson(n)

Examples

from sympy import Matrix wminus, wplus = Matrix.wilkinson(3) wminus Matrix([ [-3, 1, 0, 0, 0, 0, 0], [ 1, -2, 1, 0, 0, 0, 0], [ 0, 1, -1, 1, 0, 0, 0], [ 0, 0, 1, 0, 1, 0, 0], [ 0, 0, 0, 1, 1, 1, 0], [ 0, 0, 0, 0, 1, 2, 1], [ 0, 0, 0, 0, 0, 1, 3]]) wplus Matrix([ [3, 1, 0, 0, 0, 0, 0], [1, 2, 1, 0, 0, 0, 0], [0, 1, 1, 1, 0, 0, 0], [0, 0, 1, 0, 1, 0, 0], [0, 0, 0, 1, 1, 1, 0], [0, 0, 0, 0, 1, 2, 1], [0, 0, 0, 0, 0, 1, 3]])

References

.. [1] https://blogs.mathworks.com/cleve/2013/04/15/wilkinsons-matrices-2/ .. [2] J. H. Wilkinson, The Algebraic Eigenvalue Problem, Claredon Press, Oxford, 1965, 662 pp.

_eval_iter_values()

_eval_values()

_eval_iter_items()

_eval_atoms(*types)

_eval_free_symbols()

_eval_has(*patterns)

_eval_is_symbolic()

_eval_is_matrix_hermitian(simpfunc)

_eval_is_zero_matrix()

_eval_is_Identity()

_eval_is_diagonal()

_eval_is_lower()

_eval_is_upper()

_eval_is_lower_hessenberg()

_eval_is_upper_hessenberg()

_eval_is_symmetric(simpfunc)

_eval_is_anti_symmetric(simpfunc)

_has_positive_diagonals()

_has_nonnegative_diagonals()

atoms(*types)

Returns the atoms that form the current object.

Examples

from sympy.abc import x, y from sympy import Matrix Matrix([[x]]) Matrix([[x]]) .atoms() {x} Matrix([[x, y], [y, x]]) Matrix([ [x, y], [y, x]]) .atoms()

has(*patterns)

Test whether any subexpression matches any of the patterns.

Examples

from sympy import Matrix, SparseMatrix, Float from sympy.abc import x, y A = Matrix(((1, x), (0.2, 3))) B = SparseMatrix(((1, x), (0.2, 3))) A.has(x) True A.has(y) False A.has(Float) True B.has(x) True B.has(y) False B.has(Float) True

is_anti_symmetric(simplify=True)

Check if matrix M is an antisymmetric matrix, that is, M is a square matrix with all M[i, j] == -M[j, i].

When simplify=True (default), the sum M[i, j] + M[j, i] is simplified before testing to see if it is zero. By default, the SymPy simplify function is used. To use a custom function set simplify to a function that accepts a single argument which returns a simplified expression. To skip simplification, set simplify to False but note that although this will be faster, it may induce false negatives.

Examples

from sympy import Matrix, symbols m = Matrix(2, 2, [0, 1, -1, 0]) m Matrix([ [ 0, 1], [-1, 0]]) m.is_anti_symmetric() True x, y = symbols('x y') m = Matrix(2, 3, [0, 0, x, -y, 0, 0]) m Matrix([ [ 0, 0, x], [-y, 0, 0]]) m.is_anti_symmetric() False

from sympy.abc import x, y m = Matrix(3, 3, [0, x2 + 2*x + 1, y, ... -(x + 1)2, 0, xy, ... -y, -xy, 0])

Simplification of matrix elements is done by default so even though two elements which should be equal and opposite would not pass an equality test, the matrix is still reported as anti-symmetric:

m[0, 1] == -m[1, 0] False m.is_anti_symmetric() True

If simplify=False is used for the case when a Matrix is already simplified, this will speed things up. Here, we see that without simplification the matrix does not appear anti-symmetric:

print(m.is_anti_symmetric(simplify=False)) None

But if the matrix were already expanded, then it would appear anti-symmetric and simplification in the is_anti_symmetric routine is not needed:

m = m.expand() m.is_anti_symmetric(simplify=False) True

is_diagonal()

Check if matrix is diagonal, that is matrix in which the entries outside the main diagonal are all zero.

Examples

from sympy import Matrix, diag m = Matrix(2, 2, [1, 0, 0, 2]) m Matrix([ [1, 0], [0, 2]]) m.is_diagonal() True

m = Matrix(2, 2, [1, 1, 0, 2]) m Matrix([ [1, 1], [0, 2]]) m.is_diagonal() False

m = diag(1, 2, 3) m Matrix([ [1, 0, 0], [0, 2, 0], [0, 0, 3]]) m.is_diagonal() True

See Also

is_lower is_upper sympy.matrices.matrixbase.MatrixBase.is_diagonalizable diagonalize

is_symbolic()

Checks if any elements contain Symbols.

Examples

from sympy import Matrix from sympy.abc import x, y M = Matrix([[x, y], [1, 0]]) M.is_symbolic() True

is_symmetric(simplify=True)

Check if matrix is symmetric matrix, that is square matrix and is equal to its transpose.

By default, simplifications occur before testing symmetry. They can be skipped using 'simplify=False'; while speeding things a bit, this may however induce false negatives.

Examples

from sympy import Matrix m = Matrix(2, 2, [0, 1, 1, 2]) m Matrix([ [0, 1], [1, 2]]) m.is_symmetric() True

m = Matrix(2, 2, [0, 1, 2, 0]) m Matrix([ [0, 1], [2, 0]]) m.is_symmetric() False

m = Matrix(2, 3, [0, 0, 0, 0, 0, 0]) m Matrix([ [0, 0, 0], [0, 0, 0]]) m.is_symmetric() False

from sympy.abc import x, y m = Matrix(3, 3, [1, x2 + 2*x + 1, y, (x + 1)2, 2, 0, y, 0, 3]) m Matrix([ [ 1, x2 + 2*x + 1, y], [(x + 1)2, 2, 0], [ y, 0, 3]]) m.is_symmetric() True

If the matrix is already simplified, you may speed-up is_symmetric() test by using 'simplify=False'.

bool(m.is_symmetric(simplify=False)) False m1 = m.expand() m1.is_symmetric(simplify=False) True

values()

Return non-zero values of self.

Examples

from sympy import Matrix m = Matrix([[0, 1], [2, 3]]) m.values() [1, 2, 3]

See Also

iter_values tolist flat

iter_values()

Iterate over non-zero values of self.

Examples

from sympy import Matrix m = Matrix([[0, 1], [2, 3]]) list(m.iter_values()) [1, 2, 3]

See Also

values

iter_items()

Iterate over indices and values of nonzero items.

Examples

from sympy import Matrix m = Matrix([[0, 1], [2, 3]]) list(m.iter_items()) [((0, 1), 1), ((1, 0), 2), ((1, 1), 3)]

See Also

iter_values todok

_eval_adjoint()

_eval_applyfunc(f)

_eval_as_real_imag()

_eval_conjugate()

_eval_permute_cols(perm)

_eval_permute_rows(perm)

_eval_trace()

_eval_transpose()

Returns the transposed SparseMatrix of this SparseMatrix.

Examples

from sympy import SparseMatrix a = SparseMatrix(((1, 2), (3, 4))) a Matrix([ [1, 2], [3, 4]]) a.T Matrix([ [1, 3], [2, 4]])

applyfunc(f)

Apply a function to each element of the matrix.

Examples

from sympy import Matrix m = Matrix(2, 2, lambda i, j: i2+j) m Matrix([ [0, 1], [2, 3]]) m.applyfunc(lambda i: 2i) Matrix([ [0, 2], [4, 6]])

as_real_imag(deep=True, **hints)

Returns a tuple containing the (real, imaginary) part of matrix.

conjugate()

Return the by-element conjugation.

Examples

from sympy import SparseMatrix, I a = SparseMatrix(((1, 2 + I), (3, 4), (I, -I))) a Matrix([ [1, 2 + I], [3, 4], [I, -I]]) a.C Matrix([ [ 1, 2 - I], [ 3, 4], [-I, I]])

See Also

transpose: Matrix transposition H: Hermite conjugation sympy.matrices.matrixbase.MatrixBase.D: Dirac conjugation

doit(**hints)

evalf(n=15, subs=None, maxn=100, chop=False, strict=False, quad=None, verbose=False)

Apply evalf() to each element of self.

expand(deep=True, modulus=None, power_base=True, power_exp=True, mul=True, log=True, multinomial=True, basic=True, **hints)

Apply core.function.expand to each entry of the matrix.

Examples

from sympy.abc import x from sympy import Matrix Matrix(1, 1, [x(x+1)]) Matrix([[x(x + 1)]]) _.expand() Matrix([[x**2 + x]])

permute(perm, orientation='rows', direction='forward')

Permute the rows or columns of a matrix by the given list of swaps.

Parameters

Permutation, list, or list of lists

A representation for the permutation.

If it is Permutation, it is used directly with some resizing with respect to the matrix size.

If it is specified as list of lists, (e.g., [[0, 1], [0, 2]]), then the permutation is formed from applying the product of cycles. The direction how the cyclic product is applied is described in below.

If it is specified as a list, the list should represent an array form of a permutation. (e.g., [1, 2, 0]) which would would form the swapping function 0 \mapsto 1, 1 \mapsto 2, 2\mapsto 0.

'rows', 'cols'

A flag to control whether to permute the rows or the columns

'forward', 'backward'

A flag to control whether to apply the permutations from the start of the list first, or from the back of the list first.

For example, if the permutation specification is [[0, 1], [0, 2]],

If the flag is set to 'forward', the cycle would be formed as 0 \mapsto 2, 2 \mapsto 1, 1 \mapsto 0.

If the flag is set to 'backward', the cycle would be formed as 0 \mapsto 1, 1 \mapsto 2, 2 \mapsto 0.

If the argument perm is not in a form of list of lists, this flag takes no effect.

Examples

from sympy import eye M = eye(3) M.permute([[0, 1], [0, 2]], orientation='rows', direction='forward') Matrix([ [0, 0, 1], [1, 0, 0], [0, 1, 0]])

from sympy import eye M = eye(3) M.permute([[0, 1], [0, 2]], orientation='rows', direction='backward') Matrix([ [0, 1, 0], [0, 0, 1], [1, 0, 0]])

Notes

If a bijective function \sigma : \mathbb{N}_0 \rightarrow \mathbb{N}_0 denotes the permutation.

If the matrix A is the matrix to permute, represented as a horizontal or a vertical stack of vectors:

.. math:: A = \begin{bmatrix} a_0 \ a_1 \ \vdots \ a_{n-1} \end{bmatrix} = \begin{bmatrix} \alpha_0 & \alpha_1 & \cdots & \alpha_{n-1} \end{bmatrix}

If the matrix B is the result, the permutation of matrix rows is defined as:

.. math:: B := \begin{bmatrix} a_{\sigma(0)} \ a_{\sigma(1)} \ \vdots \ a_{\sigma(n-1)} \end{bmatrix}

And the permutation of matrix columns is defined as:

.. math:: B := \begin{bmatrix} \alpha_{\sigma(0)} & \alpha_{\sigma(1)} & \cdots & \alpha_{\sigma(n-1)} \end{bmatrix}

permute_cols(swaps, direction='forward')

Alias for self.permute(swaps, orientation='cols', direction=direction)

See Also

permute

permute_rows(swaps, direction='forward')

Alias for self.permute(swaps, orientation='rows', direction=direction)

See Also

permute

refine(assumptions=True)

Apply refine to each element of the matrix.

Examples

from sympy import Symbol, Matrix, Abs, sqrt, Q x = Symbol('x') Matrix([[Abs(x)2, sqrt(x2)],[sqrt(x2), Abs(x)2]]) Matrix([ [ Abs(x)2, sqrt(x2)], [sqrt(x2), Abs(x)2]]) _.refine(Q.real(x)) Matrix([ [ x2, Abs(x)], [Abs(x), x2]])

replace(F, G, map=False, simultaneous=True, exact=None)

Replaces Function F in Matrix entries with Function G.

Examples

from sympy import symbols, Function, Matrix F, G = symbols('F, G', cls=Function) M = Matrix(2, 2, lambda i, j: F(i+j)) ; M Matrix([ [F(0), F(1)], [F(1), F(2)]]) N = M.replace(F,G) N Matrix([ [G(0), G(1)], [G(1), G(2)]])

rot90(k=1)

Rotates Matrix by 90 degrees

Parameters

int

Specifies how many times the matrix is rotated by 90 degrees (clockwise when positive, counter-clockwise when negative).

Examples

from sympy import Matrix, symbols A = Matrix(2, 2, symbols('a:d')) A Matrix([ [a, b], [c, d]])

Rotating the matrix clockwise one time:

A.rot90(1) Matrix([ [c, a], [d, b]])

Rotating the matrix anticlockwise two times:

A.rot90(-2) Matrix([ [d, c], [b, a]])

trace()

Returns the trace of a square matrix i.e. the sum of the diagonal elements.

Examples

from sympy import Matrix A = Matrix(2, 2, [1, 2, 3, 4]) A.trace() 5

transpose()

Returns the transpose of the matrix.

Examples

from sympy import Matrix A = Matrix(2, 2, [1, 2, 3, 4]) A.transpose() Matrix([ [1, 3], [2, 4]])

from sympy import Matrix, I m=Matrix(((1, 2+I), (3, 4))) m Matrix([ [1, 2 + I], [3, 4]]) m.transpose() Matrix([ [ 1, 3], [2 + I, 4]]) m.T == m.transpose() True

See Also

conjugate: By-element conjugation

n(*args, **kwargs)

Apply evalf() to each element of self.

xreplace(rule)

Return a new matrix with xreplace applied to each entry.

Examples

from sympy.abc import x, y from sympy import SparseMatrix, Matrix SparseMatrix(1, 1, [x]) Matrix([[x]]) .xreplace({x: y}) Matrix([[y]]) Matrix().xreplace({y: x}) Matrix([[x]])

_eval_simplify(**kwargs)

_eval_trigsimp(**opts)

upper_triangular(k=0)

Return the elements on and above the kth diagonal of a matrix. If k is not specified then simply returns upper-triangular portion of a matrix

Examples

from sympy import ones A = ones(4) A.upper_triangular() Matrix([ [1, 1, 1, 1], [0, 1, 1, 1], [0, 0, 1, 1], [0, 0, 0, 1]])

A.upper_triangular(2) Matrix([ [0, 0, 1, 1], [0, 0, 0, 1], [0, 0, 0, 0], [0, 0, 0, 0]])

A.upper_triangular(-1) Matrix([ [1, 1, 1, 1], [1, 1, 1, 1], [0, 1, 1, 1], [0, 0, 1, 1]])

lower_triangular(k=0)

Return the elements on and below the kth diagonal of a matrix. If k is not specified then simply returns lower-triangular portion of a matrix

Examples

from sympy import ones A = ones(4) A.lower_triangular() Matrix([ [1, 0, 0, 0], [1, 1, 0, 0], [1, 1, 1, 0], [1, 1, 1, 1]])

A.lower_triangular(-2) Matrix([ [0, 0, 0, 0], [0, 0, 0, 0], [1, 0, 0, 0], [1, 1, 0, 0]])

A.lower_triangular(1) Matrix([ [1, 1, 0, 0], [1, 1, 1, 0], [1, 1, 1, 1], [1, 1, 1, 1]])

_eval_Abs()

_eval_add(other)

_eval_matrix_mul(other)

_eval_matrix_mul_elementwise(other)

_eval_matrix_rmul(other)

_eval_pow_by_recursion(num)

_eval_pow_by_cayley(exp)

_eval_pow_by_recursion_dotprodsimp(num, prevsimp=None)

_eval_scalar_mul(other)

_eval_scalar_rmul(other)

_eval_Mod(other)

__truediv__(other)

__matmul__(other)

__mod__(other)

multiply(other, dotprodsimp=None)

Same as mul() but with optional simplification.

Parameters

bool, optional

Specifies whether intermediate term algebraic simplification is used during matrix multiplications to control expression blowup and thus speed up calculation. Default is off.

multiply_elementwise(other)

Return the Hadamard product (elementwise product) of A and B

Examples

from sympy import Matrix A = Matrix([[0, 1, 2], [3, 4, 5]]) B = Matrix([[1, 10, 100], [100, 10, 1]]) A.multiply_elementwise(B) Matrix([ [ 0, 10, 200], [300, 40, 5]])

See Also

sympy.matrices.matrixbase.MatrixBase.cross sympy.matrices.matrixbase.MatrixBase.dot multiply

__pow__(exp)

Return self**exp a scalar or symbol.

pow(exp, method=None)

Return self**exp a scalar or symbol.

Parameters

multiply, mulsimp, jordan, cayley

If multiply then it returns exponentiation using recursion. If jordan then Jordan form exponentiation will be used. If cayley then the exponentiation is done using Cayley-Hamilton theorem. If mulsimp then the exponentiation is done using recursion with dotprodsimp. This specifies whether intermediate term algebraic simplification is used during naive matrix power to control expression blowup and thus speed up calculation. If None, then it heuristically decides which method to use.

__radd__(other)

__rmatmul__(other)

rmultiply(other, dotprodsimp=None)

Same as rmul() but with optional simplification.

Parameters

bool, optional

Specifies whether intermediate term algebraic simplification is used during matrix multiplications to control expression blowup and thus speed up calculation. Default is off.

__rsub__(a)

__sub__(a)

_eval_det_bareiss(iszerofunc=_is_zero_after_expand_mul)

_eval_det_berkowitz()

_eval_det_lu(iszerofunc=_iszero, simpfunc=None)

_eval_det_bird()

_eval_det_laplace()

_eval_determinant()

adjugate(method='berkowitz')

charpoly(x='lambda', simplify=_utilities_simplify)

cofactor(i, j, method='berkowitz')

cofactor_matrix(method='berkowitz')

det(method='bareiss', iszerofunc=None)

per()

minor(i, j, method='berkowitz')

minor_submatrix(i, j)

echelon_form(iszerofunc=_iszero, simplify=False, with_pivots=False)

rank(iszerofunc=_iszero, simplify=False)

rref_rhs(rhs)

Return reduced row-echelon form of matrix, matrix showing rhs after reduction steps. rhs must have the same number of rows as self.

Examples

from sympy import Matrix, symbols r1, r2 = symbols('r1 r2') Matrix([[1, 1], [2, 1]]).rref_rhs(Matrix([r1, r2])) (Matrix([ [1, 0], [0, 1]]), Matrix([ [ -r1 + r2], [2*r1 - r2]]))

_normalize_op_args(op, col, k, col1, col2, error_str='col')

Validate the arguments for a row/column operation. error_str can be one of "row" or "col" depending on the arguments being parsed.

_eval_col_op_multiply_col_by_const(col, k)

_eval_col_op_swap(col1, col2)

_eval_col_op_add_multiple_to_other_col(col, k, col2)

_eval_row_op_swap(row1, row2)

_eval_row_op_multiply_row_by_const(row, k)

_eval_row_op_add_multiple_to_other_row(row, k, row2)

elementary_col_op(op='n->kn', col=None, k=None, col1=None, col2=None)

Performs the elementary column operation op.

op may be one of

Text Only
1
2
3
* ``"n->kn"`` (column n goes to k*n)
* ``"n<->m"`` (swap column n and column m)
* ``"n->n+km"`` (column n goes to column n + k*column m)

Parameters

op : string; the elementary row operation col : the column to apply the column operation k : the multiple to apply in the column operation col1 : one column of a column swap col2 : second column of a column swap or column "m" in the column operation "n->n+km"

elementary_row_op(op='n->kn', row=None, k=None, row1=None, row2=None)

Performs the elementary row operation op.

op may be one of

Text Only
1
2
3
* ``"n->kn"`` (row n goes to k*n)
* ``"n<->m"`` (swap row n and row m)
* ``"n->n+km"`` (row n goes to row n + k*row m)

Parameters

op : string; the elementary row operation row : the row to apply the row operation k : the multiple to apply in the row operation row1 : one row of a row swap row2 : second row of a row swap or row "m" in the row operation "n->n+km"

columnspace(simplify=False)

rowspace(simplify=False)

eigenvals(error_when_incomplete=True, **flags)

eigenvects(error_when_incomplete=True, iszerofunc=_iszero, **flags)

bidiagonalize(upper=True)

bidiagonal_decomposition(upper=True)

jordan_form(calc_transform=True, **kwargs)

left_eigenvects(**flags)

singular_values()

diff(*args, evaluate=True, **kwargs)

Calculate the derivative of each element in the matrix.

Examples

from sympy import Matrix from sympy.abc import x, y M = Matrix([[x, y], [1, 0]]) M.diff(x) Matrix([ [1, 0], [0, 0]])

See Also

integrate limit

_eval_derivative(arg)

integrate(*args, **kwargs)

Integrate each element of the matrix. args will be passed to the integrate function.

Examples

from sympy import Matrix from sympy.abc import x, y M = Matrix([[x, y], [1, 0]]) M.integrate((x, )) Matrix([ [x2/2, xy], [ x, 0]]) M.integrate((x, 0, 2)) Matrix([ [2, 2y], [2, 0]])

See Also

limit diff

jacobian(X)

Calculates the Jacobian matrix (derivative of a vector-valued function).

Parameters

self : vector of expressions representing functions f_i(x_1, ..., x_n). X : set of x_i's in order, it can be a list or a Matrix

Both self and X can be a row or a column matrix in any order (i.e., jacobian() should always work).

Examples

from sympy import sin, cos, Matrix from sympy.abc import rho, phi X = Matrix([rhocos(phi), rhosin(phi), rho2]) Y = Matrix([rho, phi]) X.jacobian(Y) Matrix([ [cos(phi), -rhosin(phi)], [sin(phi), rhocos(phi)], [ 2rho, 0]]) X = Matrix([rhocos(phi), rhosin(phi)]) X.jacobian(Y) Matrix([ [cos(phi), -rhosin(phi)], [sin(phi), rho*cos(phi)]])

See Also

hessian wronskian

limit(*args)

Calculate the limit of each element in the matrix. args will be passed to the limit function.

Examples

from sympy import Matrix from sympy.abc import x, y M = Matrix([[x, y], [1, 0]]) M.limit(x, 2) Matrix([ [2, y], [1, 0]])

See Also

integrate diff

berkowitz_charpoly(x=Dummy('lambda'), simplify=_utilities_simplify)

berkowitz_det()

Computes determinant using Berkowitz method.

See Also

det

berkowitz_eigenvals(**flags)

Computes eigenvalues of a Matrix using Berkowitz method.

berkowitz_minors()

Computes principal minors using Berkowitz method.

berkowitz()

cofactorMatrix(method='berkowitz')

det_bareis()

det_LU_decomposition()

Compute matrix determinant using LU decomposition.

Note that this method fails if the LU decomposition itself fails. In particular, if the matrix has no inverse this method will fail.

TODO: Implement algorithm for sparse matrices (SFF), http://www.eecis.udel.edu/~saunders/papers/sffge/it5.ps.

See Also

det berkowitz_det

jordan_cell(eigenval, n)

jordan_cells(calc_transformation=True)

minorEntry(i, j, method='berkowitz')

minorMatrix(i, j)

permuteBkwd(perm)

Permute the rows of the matrix with the given permutation in reverse.

permuteFwd(perm)

Permute the rows of the matrix with the given permutation.

flat()

__array__(dtype=object, copy=None)

__len__()

Return the number of elements of self.

Implemented mainly so bool(Matrix()) == False.

_matrix_pow_by_jordan_blocks(num)

_format_str(printer=None)

irregular(ntop, *matrices, **kwargs) classmethod

Return a matrix filled by the given matrices which are listed in order of appearance from left to right, top to bottom as they first appear in the matrix. They must fill the matrix completely.

Examples

from sympy import ones, Matrix Matrix.irregular(3, ones(2,1), ones(3,3)2, ones(2,2)3, ... ones(1,1)4, ones(2,2)5, ones(1,2)6, ones(1,2)7) Matrix([ [1, 2, 2, 2, 3, 3], [1, 2, 2, 2, 3, 3], [4, 2, 2, 2, 5, 5], [6, 6, 7, 7, 5, 5]])

_handle_ndarray(arg) classmethod

_handle_creation_inputs(*args, **kwargs) classmethod

Return the number of rows, cols and flat matrix elements.

Examples

from sympy import Matrix, I

Matrix can be constructed as follows:

  • from a nested list of iterables

Matrix( ((1, 2+I), (3, 4)) ) Matrix([ [1, 2 + I], [3, 4]])

  • from un-nested iterable (interpreted as a column)

Matrix( [1, 2] ) Matrix([ [1], [2]])

  • from un-nested iterable with dimensions

Matrix(1, 2, [1, 2] ) Matrix([[1, 2]])

  • from no arguments (a 0 x 0 matrix)

Matrix() Matrix(0, 0, [])

  • from a rule

Matrix(2, 2, lambda i, j: i/(j + 1) ) Matrix([ [0, 0], [1, 1/2]])

See Also

irregular - filling a matrix with irregular blocks

_setitem(key, value)

Helper to set value at location given by key.

Examples

from sympy import Matrix, I, zeros, ones m = Matrix(((1, 2+I), (3, 4))) m Matrix([ [1, 2 + I], [3, 4]]) m[1, 0] = 9 m Matrix([ [1, 2 + I], [9, 4]]) m[1, 0] = [[0, 1]]

To replace row r you assign to position r*m where m is the number of columns:

M = zeros(4) m = M.cols M[3m] = ones(1, m)2; M Matrix([ [0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0], [2, 2, 2, 2]])

And to replace column c you can assign to position c:

M[2] = ones(m, 1)*4; M Matrix([ [0, 0, 4, 0], [0, 0, 4, 0], [0, 0, 4, 0], [2, 2, 4, 2]])

add(b)

Return self + b.

condition_number()

Returns the condition number of a matrix.

This is the maximum singular value divided by the minimum singular value

Examples

from sympy import Matrix, S A = Matrix([[1, 0, 0], [0, 10, 0], [0, 0, S.One/10]]) A.condition_number() 100

See Also

singular_values

cross(b)

Return the cross product of self and b relaxing the condition of compatible dimensions: if each has 3 elements, a matrix of the same type and shape as self will be returned. If b has the same shape as self then common identities for the cross product (like a \times b = - b \times a) will hold.

Parameters

Text Only
1
b : 3x1 or 1x3 Matrix

See Also

dot hat vee multiply multiply_elementwise

hat()

Return the skew-symmetric matrix representing the cross product, so that self.hat() * b is equivalent to self.cross(b).

Examples

Calling hat creates a skew-symmetric 3x3 Matrix from a 3x1 Matrix:

from sympy import Matrix a = Matrix([1, 2, 3]) a.hat() Matrix([ [ 0, -3, 2], [ 3, 0, -1], [-2, 1, 0]])

Multiplying it with another 3x1 Matrix calculates the cross product:

b = Matrix([3, 2, 1]) a.hat() * b Matrix([ [-4], [ 8], [-4]])

Which is equivalent to calling the cross method:

a.cross(b) Matrix([ [-4], [ 8], [-4]])

See Also

dot cross vee multiply multiply_elementwise

vee()

Return a 3x1 vector from a skew-symmetric matrix representing the cross product, so that self * b is equivalent to self.vee().cross(b).

Examples

Calling vee creates a vector from a skew-symmetric Matrix:

from sympy import Matrix A = Matrix([[0, -3, 2], [3, 0, -1], [-2, 1, 0]]) a = A.vee() a Matrix([ [1], [2], [3]])

Calculating the matrix product of the original matrix with a vector is equivalent to a cross product:

b = Matrix([3, 2, 1]) A * b Matrix([ [-4], [ 8], [-4]])

a.cross(b) Matrix([ [-4], [ 8], [-4]])

vee can also be used to retrieve angular velocity expressions. Defining a rotation matrix:

from sympy import rot_ccw_axis3, trigsimp from sympy.physics.mechanics import dynamicsymbols theta = dynamicsymbols('theta') R = rot_ccw_axis3(theta) R Matrix([ [cos(theta(t)), -sin(theta(t)), 0], [sin(theta(t)), cos(theta(t)), 0], [ 0, 0, 1]])

We can retrive the angular velocity:

Omega = R.T * R.diff() Omega = trigsimp(Omega) Omega.vee() Matrix([ [ 0], [ 0], [Derivative(theta(t), t)]])

See Also

dot cross hat multiply multiply_elementwise

dot(b, hermitian=None, conjugate_convention=None)

Return the dot or inner product of two vectors of equal length. Here self must be a Matrix of size 1 x n or n x 1, and b must be either a matrix of size 1 x n, n x 1, or a list/tuple of length n. A scalar is returned.

By default, dot does not conjugate self or b, even if there are complex entries. Set hermitian=True (and optionally a conjugate_convention) to compute the hermitian inner product.

Possible kwargs are hermitian and conjugate_convention.

If conjugate_convention is "left", "math" or "maths", the conjugate of the first vector (self) is used. If "right" or "physics" is specified, the conjugate of the second vector b is used.

Examples

from sympy import Matrix M = Matrix([[1, 2, 3], [4, 5, 6], [7, 8, 9]]) v = Matrix([1, 1, 1]) M.row(0).dot(v) 6 M.col(0).dot(v) 12 v = [3, 2, 1] M.row(0).dot(v) 10

from sympy import I q = Matrix([1I, 1I, 1*I]) q.dot(q, hermitian=False) -3

q.dot(q, hermitian=True) 3

q1 = Matrix([1, 1, 1I]) q.dot(q1, hermitian=True, conjugate_convention="maths") 1 - 2I q.dot(q1, hermitian=True, conjugate_convention="physics") 1 + 2*I

See Also

cross multiply multiply_elementwise

dual()

Returns the dual of a matrix.

A dual of a matrix is:

(1/2)*levicivita(i, j, k, l)*M(k, l) summed over indices k and l

Since the levicivita method is anti_symmetric for any pairwise exchange of indices, the dual of a symmetric matrix is the zero matrix. Strictly speaking the dual defined here assumes that the 'matrix' M is a contravariant anti_symmetric second rank tensor, so that the dual is a covariant second rank tensor.

_eval_matrix_exp_jblock()

A helper function to compute an exponential of a Jordan block matrix

Examples

from sympy import Symbol, Matrix l = Symbol('lamda')

A trivial example of 1*1 Jordan block:

m = Matrix.jordan_block(1, l) m._eval_matrix_exp_jblock() Matrix([[exp(lamda)]])

An example of 3*3 Jordan block:

m = Matrix.jordan_block(3, l) m._eval_matrix_exp_jblock() Matrix([ [exp(lamda), exp(lamda), exp(lamda)/2], [ 0, exp(lamda), exp(lamda)], [ 0, 0, exp(lamda)]])

References

.. [1] https://en.wikipedia.org/wiki/Matrix_function#Jordan_decomposition

analytic_func(f, x)

Computes f(A) where A is a Square Matrix and f is an analytic function.

Examples

from sympy import Symbol, Matrix, S, log

x = Symbol('x') m = Matrix([[S(5)/4, S(3)/4], [S(3)/4, S(5)/4]]) f = log(x) m.analytic_func(f, x) Matrix([ [ 0, log(2)], [log(2), 0]])

Parameters

Expr

Analytic Function

x : Symbol parameter of f

exp()

Return the exponential of a square matrix.

Examples

from sympy import Symbol, Matrix

t = Symbol('t') m = Matrix([[0, 1], [-1, 0]]) * t m.exp() Matrix([ [ exp(It)/2 + exp(-It)/2, -Iexp(It)/2 + Iexp(-It)/2], [Iexp(It)/2 - Iexp(-It)/2, exp(It)/2 + exp(-It)/2]])

_eval_matrix_log_jblock()

Helper function to compute logarithm of a jordan block.

Examples

from sympy import Symbol, Matrix l = Symbol('lamda')

A trivial example of 1*1 Jordan block:

m = Matrix.jordan_block(1, l) m._eval_matrix_log_jblock() Matrix([[log(lamda)]])

An example of 3*3 Jordan block:

m = Matrix.jordan_block(3, l) m._eval_matrix_log_jblock() Matrix([ [log(lamda), 1/lamda, -1/(2lamda*2)], [ 0, log(lamda), 1/lamda], [ 0, 0, log(lamda)]])

log(simplify=cancel)

Return the logarithm of a square matrix.

Parameters

function, bool

The function to simplify the result with.

Default is cancel, which is effective to reduce the expression growing for taking reciprocals and inverses for symbolic matrices.

Examples

from sympy import S, Matrix

Examples for positive-definite matrices:

m = Matrix([[1, 1], [0, 1]]) m.log() Matrix([ [0, 1], [0, 0]])

m = Matrix([[S(5)/4, S(3)/4], [S(3)/4, S(5)/4]]) m.log() Matrix([ [ 0, log(2)], [log(2), 0]])

Examples for non positive-definite matrices:

m = Matrix([[S(3)/4, S(5)/4], [S(5)/4, S(3)/4]]) m.log() Matrix([ [ Ipi/2, log(2) - Ipi/2], [log(2) - Ipi/2, Ipi/2]])

m = Matrix( ... [[0, 0, 0, 1], ... [0, 0, 1, 0], ... [0, 1, 0, 0], ... [1, 0, 0, 0]]) m.log() Matrix([ [ Ipi/2, 0, 0, -Ipi/2], [ 0, Ipi/2, -Ipi/2, 0], [ 0, -Ipi/2, Ipi/2, 0], [-Ipi/2, 0, 0, Ipi/2]])

is_nilpotent()

Checks if a matrix is nilpotent.

A matrix B is nilpotent if for some integer k, B**k is a zero matrix.

Examples

from sympy import Matrix a = Matrix([[0, 0, 0], [1, 0, 0], [1, 1, 0]]) a.is_nilpotent() True

a = Matrix([[1, 0, 1], [1, 0, 0], [1, 1, 0]]) a.is_nilpotent() False

key2bounds(keys)

Converts a key with potentially mixed types of keys (integer and slice) into a tuple of ranges and raises an error if any index is out of self's range.

See Also

key2ij

key2ij(key)

Converts key into canonical form, converting integers or indexable items into valid integers for self's range or returning slices unchanged.

See Also

key2bounds

norm(ord=None)

Return the Norm of a Matrix or Vector.

In the simplest case this is the geometric size of the vector Other norms can be specified by the ord parameter

===== ============================ ========================== ord norm for matrices norm for vectors ===== ============================ ========================== None Frobenius norm 2-norm 'fro' Frobenius norm - does not exist inf maximum row sum max(abs(x)) -inf -- min(abs(x)) 1 maximum column sum as below -1 -- as below 2 2-norm (largest sing. value) as below -2 smallest singular value as below other - does not exist sum(abs(x)ord)(1./ord) ===== ============================ ==========================

Examples

from sympy import Matrix, Symbol, trigsimp, cos, sin, oo x = Symbol('x', real=True) v = Matrix([cos(x), sin(x)]) trigsimp( v.norm() ) 1 v.norm(10) (sin(x)10 + cos(x)10)**(1/10) A = Matrix([[1, 1], [1, 1]]) A.norm(1) # maximum sum of absolute values of A is 2 2 A.norm(2) # Spectral norm (max of |Ax|/|x| under 2-vector-norm) 2 A.norm(-2) # Inverse spectral norm (smallest singular value) 0 A.norm() # Frobenius Norm 2 A.norm(oo) # Infinity Norm 2 Matrix([1, -2]).norm(oo) 2 Matrix([-1, 2]).norm(-oo) 1

See Also

normalized

print_nonzero(symb='X')

Shows location of non-zero entries for fast shape lookup.

Examples

from sympy import Matrix, eye m = Matrix(2, 3, lambda i, j: i*3+j) m Matrix([ [0, 1, 2], [3, 4, 5]]) m.print_nonzero() [ XX][XXX] m = eye(4) m.print_nonzero("x") [x ][ x ] [ x ][ x]

project(v)

Return the projection of self onto the line containing v.

Examples

from sympy import Matrix, S, sqrt V = Matrix([sqrt(3)/2, S.Half]) x = Matrix([[1, 0]]) V.project(x) Matrix([[sqrt(3)/2, 0]]) V.project(-x) Matrix([[sqrt(3)/2, 0]])

table(printer, rowstart='[', rowend=']', rowsep='\n', colsep=', ', align='right')

String form of Matrix as a table.

printer is the printer to use for on the elements (generally something like StrPrinter())

rowstart is the string used to start each row (by default '[').

rowend is the string used to end each row (by default ']').

rowsep is the string used to separate rows (by default a newline).

colsep is the string used to separate columns (by default ', ').

align defines how the elements are aligned. Must be one of 'left', 'right', or 'center'. You can also use '<', '>', and '^' to mean the same thing, respectively.

This is used by the string printer for Matrix.

Examples

from sympy import Matrix, StrPrinter M = Matrix([[1, 2], [-33, 4]]) printer = StrPrinter() M.table(printer) '[ 1, 2]\n[-33, 4]' print(M.table(printer)) [ 1, 2][-33, 4] print(M.table(printer, rowsep=',\n')) [ 1, 2], [-33, 4] print('[%s]' % M.table(printer, rowsep=',\n')) [[ 1, 2], [-33, 4]] print(M.table(printer, colsep=' ')) [ 1 2][-33 4] print(M.table(printer, align='center')) [ 1 , 2][-33, 4] print(M.table(printer, rowstart='{', rowend='}')) { 1, 2}

rank_decomposition(iszerofunc=_iszero, simplify=False)

cholesky(hermitian=True)

LDLdecomposition(hermitian=True)

LUdecomposition(iszerofunc=_iszero, simpfunc=None, rankcheck=False)

LUdecomposition_Simple(iszerofunc=_iszero, simpfunc=None, rankcheck=False)

LUdecompositionFF()

upper_hessenberg_decomposition()

diagonal_solve(rhs)

lower_triangular_solve(rhs)

upper_triangular_solve(rhs)

cholesky_solve(rhs)

LDLsolve(rhs)

LUsolve(rhs, iszerofunc=_iszero)

QRsolve(b)

gauss_jordan_solve(B, freevar=False)

pinv_solve(B, arbitrary_matrix=None)

pinv(method='RD')

inverse_ADJ(iszerofunc=_iszero)

inverse_BLOCK(iszerofunc=_iszero)

inverse_GE(iszerofunc=_iszero)

inverse_LU(iszerofunc=_iszero)

inverse_CH(iszerofunc=_iszero)

inverse_LDL(iszerofunc=_iszero)

inverse_QR(iszerofunc=_iszero)

inv(method=None, iszerofunc=_iszero, try_block_diag=False)

connected_components()

connected_components_decomposition()

strongly_connected_components()

strongly_connected_components_decomposition(lower=True)

to_DM(domain=None, **kwargs)

Convert to a :class:~.DomainMatrix.

Examples

from sympy import Matrix M = Matrix([[1, 2], [3, 4]]) M.to_DM() DomainMatrix({0: {0: 1, 1: 2}, 1: {0: 3, 1: 4}}, (2, 2), ZZ)

The :meth:DomainMatrix.to_Matrix method can be used to convert back:

M.to_DM().to_Matrix() == M True

The domain can be given explicitly or otherwise it will be chosen by :func:construct_domain. Any keyword arguments (besides domain) are passed to :func:construct_domain:

from sympy import QQ, symbols x = symbols('x') M = Matrix([[x, 1], [1, x]]) M Matrix([ [x, 1], [1, x]]) M.to_DM().domain ZZ[x] M.to_DM(field=True).domain ZZ(x) M.to_DM(domain=QQ[x]).domain QQ[x]

See Also

DomainMatrix DomainMatrix.to_Matrix DomainMatrix.convert_to DomainMatrix.choose_domain construct_domain

_unify_element_sympy(rep, element) classmethod

_dod_to_DomainMatrix(rows, cols, dod, types) classmethod

_flat_list_to_DomainMatrix(rows, cols, flat_list) classmethod

_smat_to_DomainMatrix(rows, cols, smat) classmethod

equals(other, failing_expression=False)

Applies equals to corresponding elements of the matrices, trying to prove that the elements are equivalent, returning True if they are, False if any pair is not, and None (or the first failing expression if failing_expression is True) if it cannot be decided if the expressions are equivalent or not. This is, in general, an expensive operation.

Examples

from sympy import Matrix from sympy.abc import x A = Matrix([x(x - 1), 0]) B = Matrix([x*2 - x, 0]) A == B False A.simplify() == B.simplify() True A.equals(B) True A.equals(2) False

See Also

sympy.core.expr.Expr.equals

inv_mod(M, m)

Returns the inverse of the integer matrix M modulo m.

Examples

from sympy import Matrix A = Matrix(2, 2, [1, 2, 3, 4]) A.inv_mod(5) Matrix([ [3, 1], [4, 2]]) A.inv_mod(3) Matrix([ [1, 1], [0, 1]])

lll(delta=0.75)

LLL-reduced basis for the rowspace of a matrix of integers.

Performs the Lenstra–Lenstra–Lovász (LLL) basis reduction algorithm.

The implementation is provided by :class:~DomainMatrix. See :meth:~DomainMatrix.lll for more details.

Examples

from sympy import Matrix M = Matrix([[1, 0, 0, 0, -20160], ... [0, 1, 0, 0, 33768], ... [0, 0, 1, 0, 39578], ... [0, 0, 0, 1, 47757]]) M.lll() Matrix([ [ 10, -3, -2, 8, -4], [ 3, -9, 8, 1, -11], [ -3, 13, -9, -3, -9], [-12, -7, -11, 9, -1]])

See Also

lll_transform sympy.polys.matrices.domainmatrix.DomainMatrix.lll

lll_transform(delta=0.75)

LLL-reduced basis and transformation matrix.

Performs the Lenstra–Lenstra–Lovász (LLL) basis reduction algorithm.

The implementation is provided by :class:~DomainMatrix. See :meth:~DomainMatrix.lll_transform for more details.

Examples

from sympy import Matrix M = Matrix([[1, 0, 0, 0, -20160], ... [0, 1, 0, 0, 33768], ... [0, 0, 1, 0, 39578], ... [0, 0, 0, 1, 47757]]) B, T = M.lll_transform() B Matrix([ [ 10, -3, -2, 8, -4], [ 3, -9, 8, 1, -11], [ -3, 13, -9, -3, -9], [-12, -7, -11, 9, -1]]) T Matrix([ [ 10, -3, -2, 8], [ 3, -9, 8, 1], [ -3, 13, -9, -3], [-12, -7, -11, 9]])

The transformation matrix maps the original basis to the LLL-reduced basis:

T * M == B True

See Also

lll sympy.polys.matrices.domainmatrix.DomainMatrix.lll_transform

__new__(*args, **kwargs)

_fromrep(rep) classmethod

as_mutable()

Returns a mutable version of this matrix

Examples

from sympy import ImmutableMatrix X = ImmutableMatrix([[1, 2], [3, 4]]) Y = X.as_mutable() Y[1, 1] = 5 # Can set values in Y Y Matrix([ [1, 2], [3, 5]])

__setitem__(key, value)

Examples

from sympy import Matrix, I, zeros, ones m = Matrix(((1, 2+I), (3, 4))) m Matrix([ [1, 2 + I], [3, 4]]) m[1, 0] = 9 m Matrix([ [1, 2 + I], [9, 4]]) m[1, 0] = [[0, 1]]

To replace row r you assign to position r*m where m is the number of columns:

M = zeros(4) m = M.cols M[3m] = ones(1, m)2; M Matrix([ [0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0], [2, 2, 2, 2]])

And to replace column c you can assign to position c:

M[2] = ones(m, 1)*4; M Matrix([ [0, 0, 4, 0], [0, 0, 4, 0], [0, 0, 4, 0], [2, 2, 4, 2]])

col_op(j, f)

In-place operation on col j using two-arg functor whose args are interpreted as (self[i, j], i).

Examples

from sympy import eye M = eye(3) M.col_op(1, lambda v, i: v + 2*M[i, 0]); M Matrix([ [1, 2, 0], [0, 1, 0], [0, 0, 1]])

See Also

col row_op

col_swap(i, j)

Swap the two given columns of the matrix in-place.

Examples

from sympy import Matrix M = Matrix([[1, 0], [1, 0]]) M Matrix([ [1, 0], [1, 0]]) M.col_swap(0, 1) M Matrix([ [0, 1], [0, 1]])

See Also

col row_swap

row_op(i, f)

In-place operation on row i using two-arg functor whose args are interpreted as (self[i, j], j).

Examples

from sympy import eye M = eye(3) M.row_op(1, lambda v, j: v + 2*M[0, j]); M Matrix([ [1, 0, 0], [2, 1, 0], [0, 0, 1]])

See Also

row zip_row_op col_op

row_mult(i, factor)

Multiply the given row by the given factor in-place.

Examples

from sympy import eye M = eye(3) M.row_mult(1,7); M Matrix([ [1, 0, 0], [0, 7, 0], [0, 0, 1]])

row_add(s, t, k)

Add k times row s (source) to row t (target) in place.

Examples

from sympy import eye M = eye(3) M.row_add(0, 2,3); M Matrix([ [1, 0, 0], [0, 1, 0], [3, 0, 1]])

row_swap(i, j)

Swap the two given rows of the matrix in-place.

Examples

from sympy import Matrix M = Matrix([[0, 1], [1, 0]]) M Matrix([ [0, 1], [1, 0]]) M.row_swap(0, 1) M Matrix([ [1, 0], [0, 1]])

See Also

row col_swap

zip_row_op(i, k, f)

In-place operation on row i using two-arg functor whose args are interpreted as (self[i, j], self[k, j]).

Examples

from sympy import eye M = eye(3) M.zip_row_op(1, 0, lambda v, u: v + 2*u); M Matrix([ [1, 0, 0], [2, 1, 0], [0, 0, 1]])

See Also

row row_op col_op

copyin_list(key, value)

Copy in elements from a list.

Parameters

slice

The section of this matrix to replace.

value : iterable The iterable to copy values from.

Examples

from sympy import eye I = eye(3) I[:2, 0] = [1, 2] # col I Matrix([ [1, 0, 0], [2, 1, 0], [0, 0, 1]]) I[1, :2] = [[3, 4]] I Matrix([ [1, 0, 0], [3, 4, 0], [0, 0, 1]])

See Also

copyin_matrix

copyin_matrix(key, value)

Copy in values from a matrix into the given bounds.

Parameters

slice

The section of this matrix to replace.

value : Matrix The matrix to copy values from.

Examples

from sympy import Matrix, eye M = Matrix([[0, 1], [2, 3], [4, 5]]) I = eye(3) I[:3, :2] = M I Matrix([ [0, 1, 0], [2, 3, 0], [4, 5, 1]]) I[0, 1] = M I Matrix([ [0, 0, 1], [2, 2, 3], [4, 4, 5]])

See Also

copyin_list

fill(value)

Fill self with the given value.

Notes

Unless many values are going to be deleted (i.e. set to zero) this will create a matrix that is slower than a dense matrix in operations.

Examples

from sympy import SparseMatrix M = SparseMatrix.zeros(3); M Matrix([ [0, 0, 0], [0, 0, 0], [0, 0, 0]]) M.fill(1); M Matrix([ [1, 1, 1], [1, 1, 1], [1, 1, 1]])

See Also

zeros ones

_eval_inverse(**kwargs)

as_immutable()

Returns an Immutable version of this Matrix