Hot-keys on this page
r m x p toggle line displays
j k next/prev highlighted chunk
0 (zero) top of page
1 (one) first highlighted chunk
ShapeError, a2idx, classof)
"""Returns True if x is zero."""
"""Return portion of self defined by key. If the key involves a slice then a list will be returned (if key is a single slice) or a matrix (if key was a tuple involving a slice).
Examples ========
>>> from sympy import Matrix, I >>> m = Matrix([ ... [1, 2 + I], ... [3, 4 ]])
If the key is a tuple that doesn't involve a slice then that element is returned:
>>> m[1, 0] 3
When a tuple key involves a slice, a matrix is returned. Here, the first column is selected (all rows, column 0):
>>> m[:, 0] Matrix([ [1], [3]])
If the slice is not a tuple then it selects from the underlying list of elements that are arranged in row order and a list is returned if a slice is involved:
>>> m[0] 1 >>> m[::2] [1, 3] """ # XXX remove list() when PY2 support is dropped else: # XXX remove list() when PY2 support is dropped else: else: # row-wise decomposition of matrix
raise NotImplementedError()
def is_Identity(self):
"""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() []
""" for i in range(0, len(self), self.cols)]
"""Elementary row selector.
Examples ========
>>> from sympy import eye >>> eye(2).row(0) Matrix([[1, 0]])
See Also ========
col row_op row_swap row_del row_join row_insert """
"""Elementary column selector.
Examples ========
>>> from sympy import eye >>> eye(2).col(0) Matrix([ [1], [0]])
See Also ========
row col_op col_swap col_del col_join col_insert """
"""Calculate the trace of a square matrix.
Examples ========
>>> from sympy.matrices import eye >>> eye(3).trace() 3
"""
"""Matrix transposition.
Examples ========
>>> 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 """
"""By-element conjugation.
See Also ========
transpose: Matrix transposition H: Hermite conjugation D: Dirac conjugation """ lambda i, j: self[i, j].conjugate())
"""Return the matrix inverse using the method indicated (default is Gauss elimination).
kwargs ======
method : ('GE', 'LU', or 'ADJ') iszerofunc try_block_diag
Notes =====
According to the ``method`` keyword, it calls the appropriate method:
GE .... inverse_GE(); default LU .... inverse_LU() ADJ ... inverse_ADJ()
According to the ``try_block_diag`` keyword, it will try to form block diagonal matrices using the method get_diag_blocks(), invert these individually, and then reconstruct the full inverse matrix.
Note, the GE and LU methods may require the matrix to be simplified before it is inverted in order to properly detect zeros during pivoting. In difficult cases a custom zero detection function can be provided by setting the ``iszerosfunc`` argument to a function that should return True if its argument is zero. The ADJ routine computes the determinant and uses that to detect singular matrices in addition to testing for zeros on the diagonal.
See Also ========
inverse_LU inverse_GE inverse_ADJ """
else: # make sure to add an invertibility check (as in inverse_LU) # if a new method is added. raise ValueError("Inversion method unrecognized")
"""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.matrices import Matrix >>> from sympy.abc import x >>> from sympy import cos >>> 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.equals """ return False rv = ans except AttributeError: return False
return False
"""Helper function of cholesky. Without the error checks. To be used privately. """ sum(L[i, k]*L[j, k] for k in range(j))) sum(L[i, k]**2 for k in range(i)))
"""Helper function of LDLdecomposition. Without the error checks. To be used privately. """ L[i, k]*L[j, k]*D[k, k] for k in range(j))) for k in range(i))
"""Helper function of function lower_triangular_solve. Without the error checks. To be used privately. """ raise TypeError("Matrix must be non-singular.") for k in range(i))) / self[i, i]
"""Helper function of function upper_triangular_solve. Without the error checks, to be used privately. """ raise ValueError("Matrix must be non-singular.") for k in range(i + 1, self.rows))) / self[i, i]
"""Helper function of function diagonal_solve, without the error checks, to be used privately. """
"""Apply a function to each element of the matrix.
Examples ========
>>> from sympy import Matrix >>> m = Matrix(2, 2, lambda i, j: i*2+j) >>> m Matrix([ [0, 1], [2, 3]]) >>> m.applyfunc(lambda i: 2*i) Matrix([ [0, 2], [4, 6]])
"""
"""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]])
"""
"""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]]) """
"""Returns an Immutable version of this Matrix """
"""Return an r x c matrix of zeros, square if c is omitted."""
def eye(cls, n): """Return an n x n identity matrix."""
############################ # Mutable matrix operators # ############################
def __add__(self, other):
def __radd__(self, other): return super(DenseMatrix, self).__radd__(_force_mutable(other))
def __sub__(self, other):
def __rsub__(self, other): return super(DenseMatrix, self).__rsub__(_force_mutable(other))
def __mul__(self, other):
def __rmul__(self, other):
def __div__(self, other):
def __truediv__(self, other):
def __pow__(self, other):
def __rpow__(self, other): raise NotImplementedError("Matrix Power not defined")
"""Return a matrix as a Matrix, otherwise return x.""" a = x.__array__() if len(a.shape) == 0: return sympify(a) return Matrix(x)
def _new(cls, *args, **kwargs):
"""
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[3*m] = 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]]) """
"""Copy in values from a matrix into the given bounds.
Parameters ==========
key : slice The section of this matrix to replace. value : Matrix The matrix to copy values from.
Examples ========
>>> from sympy.matrices 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 """ "same dimensions " "as the in sub-Matrix given by `key`."))
"""Copy in elements from a list.
Parameters ==========
key : slice The section of this matrix to replace. value : iterable The iterable to copy values from.
Examples ========
>>> from sympy.matrices 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 """
"""In-place operation on row ``i`` using two-arg functor whose args are interpreted as ``(self[i, j], self[k, j])``.
Examples ========
>>> from sympy.matrices 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
"""
"""In-place operation on row ``i`` using two-arg functor whose args are interpreted as ``(self[i, j], j)``.
Examples ========
>>> from sympy.matrices 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
"""
"""In-place operation on col j using two-arg functor whose args are interpreted as (self[i, j], i).
Examples ========
>>> from sympy.matrices 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 """
"""Swap the two given rows of the matrix in-place.
Examples ========
>>> from sympy.matrices 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 """
"""Swap the two given columns of the matrix in-place.
Examples ========
>>> from sympy.matrices 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 """
"""Delete the given row.
Examples ========
>>> from sympy.matrices import eye >>> M = eye(3) >>> M.row_del(1) >>> M Matrix([ [1, 0, 0], [0, 0, 1]])
See Also ========
row col_del """
"""Delete the given column.
Examples ========
>>> from sympy.matrices import eye >>> M = eye(3) >>> M.col_del(1) >>> M Matrix([ [1, 0], [0, 0], [0, 1]])
See Also ========
col row_del """
# Utility functions """Applies simplify to the elements of a matrix in place.
This is a shortcut for M.applyfunc(lambda x: simplify(x, ratio, measure))
See Also ========
sympy.simplify.simplify.simplify """ measure=measure)
"""Fill the matrix with the scalar value.
See Also ========
zeros ones """
########### # Numpy Utility Functions: # list2numpy, matrix2numpy, symmarray, rot_axis[123] ###########
def list2numpy(l, dtype=object): # pragma: no cover """Converts python list of SymPy expressions to a NumPy array.
See Also ========
matrix2numpy """ from numpy import empty a = empty(len(l), dtype) for i, s in enumerate(l): a[i] = s return a
def matrix2numpy(m, dtype=object): # pragma: no cover """Converts SymPy's matrix to a NumPy array.
See Also ========
list2numpy """ from numpy import empty a = empty(m.shape, dtype) for i in range(m.rows): for j in range(m.cols): a[i, j] = m[i, j] return a
def symarray(prefix, shape): # pragma: no cover """Create a numpy ndarray of symbols (as an object array).
The created symbols are named ``prefix_i1_i2_``... You should thus provide a non-empty prefix if you want your symbols to be unique for different output arrays, as SymPy symbols with identical names are the same object.
Parameters ----------
prefix : string A prefix prepended to the name of every symbol.
shape : int or tuple Shape of the created array. If an int, the array is one-dimensional; for more than one dimension the shape must be a tuple.
Examples ======== These doctests require numpy.
>>> from sympy import symarray >>> symarray('', 3) [_0 _1 _2]
If you want multiple symarrays to contain distinct symbols, you *must* provide unique prefixes:
>>> a = symarray('', 3) >>> b = symarray('', 3) >>> a[0] == b[0] True >>> a = symarray('a', 3) >>> b = symarray('b', 3) >>> a[0] == b[0] False
Creating symarrays with a prefix:
>>> symarray('a', 3) [a_0 a_1 a_2]
For more than one dimension, the shape must be given as a tuple:
>>> symarray('a', (2, 3)) [[a_0_0 a_0_1 a_0_2] [a_1_0 a_1_1 a_1_2]] >>> symarray('a', (2, 3, 2)) [[[a_0_0_0 a_0_0_1] [a_0_1_0 a_0_1_1] [a_0_2_0 a_0_2_1]] <BLANKLINE> [[a_1_0_0 a_1_0_1] [a_1_1_0 a_1_1_1] [a_1_2_0 a_1_2_1]]]
""" from numpy import empty, ndindex arr = empty(shape, dtype=object) for index in ndindex(shape): arr[index] = Symbol('%s_%s' % (prefix, '_'.join(map(str, index)))) return arr
"""Returns a rotation matrix for a rotation of theta (in radians) about the 3-axis.
Examples ========
>>> from sympy import pi >>> from sympy.matrices import rot_axis3
A rotation of pi/3 (60 degrees):
>>> theta = pi/3 >>> rot_axis3(theta) Matrix([ [ 1/2, sqrt(3)/2, 0], [-sqrt(3)/2, 1/2, 0], [ 0, 0, 1]])
If we rotate by pi/2 (90 degrees):
>>> rot_axis3(pi/2) Matrix([ [ 0, 1, 0], [-1, 0, 0], [ 0, 0, 1]])
See Also ========
rot_axis1: Returns a rotation matrix for a rotation of theta (in radians) about the 1-axis rot_axis2: Returns a rotation matrix for a rotation of theta (in radians) about the 2-axis """ (-st, ct, 0), (0, 0, 1))
"""Returns a rotation matrix for a rotation of theta (in radians) about the 2-axis.
Examples ========
>>> from sympy import pi >>> from sympy.matrices import rot_axis2
A rotation of pi/3 (60 degrees):
>>> theta = pi/3 >>> rot_axis2(theta) Matrix([ [ 1/2, 0, -sqrt(3)/2], [ 0, 1, 0], [sqrt(3)/2, 0, 1/2]])
If we rotate by pi/2 (90 degrees):
>>> rot_axis2(pi/2) Matrix([ [0, 0, -1], [0, 1, 0], [1, 0, 0]])
See Also ========
rot_axis1: Returns a rotation matrix for a rotation of theta (in radians) about the 1-axis rot_axis3: Returns a rotation matrix for a rotation of theta (in radians) about the 3-axis """ (0, 1, 0), (st, 0, ct))
"""Returns a rotation matrix for a rotation of theta (in radians) about the 1-axis.
Examples ========
>>> from sympy import pi >>> from sympy.matrices import rot_axis1
A rotation of pi/3 (60 degrees):
>>> theta = pi/3 >>> rot_axis1(theta) Matrix([ [1, 0, 0], [0, 1/2, sqrt(3)/2], [0, -sqrt(3)/2, 1/2]])
If we rotate by pi/2 (90 degrees):
>>> rot_axis1(pi/2) Matrix([ [1, 0, 0], [0, 0, 1], [0, -1, 0]])
See Also ========
rot_axis2: Returns a rotation matrix for a rotation of theta (in radians) about the 2-axis rot_axis3: Returns a rotation matrix for a rotation of theta (in radians) about the 3-axis """ (0, ct, st), (0, -st, ct))
############### # Functions ###############
"""Return the Hadamard product (elementwise product) of A and B
>>> from sympy.matrices import matrix_multiply_elementwise >>> from sympy.matrices import Matrix >>> A = Matrix([[0, 1, 2], [3, 4, 5]]) >>> B = Matrix([[1, 10, 100], [100, 10, 1]]) >>> matrix_multiply_elementwise(A, B) Matrix([ [ 0, 10, 200], [300, 40, 5]])
See Also ========
__mul__ """ lambda i, j: A[i, j]*B[i, j])
"""Returns a matrix of ones with ``r`` rows and ``c`` columns; if ``c`` is omitted a square matrix will be returned.
See Also ========
zeros eye diag """
"""Returns a matrix of zeros with ``r`` rows and ``c`` columns; if ``c`` is omitted a square matrix will be returned.
See Also ========
ones eye diag """
"""Create square identity matrix n x n
See Also ========
diag zeros ones """
"""Create a sparse, diagonal matrix from a list of diagonal values.
Notes =====
When arguments are matrices they are fitted in resultant matrix.
The returned matrix is a mutable, dense matrix. To make it a different type, send the desired class for keyword ``cls``.
Examples ========
>>> from sympy.matrices import diag, Matrix, ones >>> diag(1, 2, 3) Matrix([ [1, 0, 0], [0, 2, 0], [0, 0, 3]]) >>> diag(*[1, 2, 3]) Matrix([ [1, 0, 0], [0, 2, 0], [0, 0, 3]])
The diagonal elements can be matrices; diagonal filling will continue on the diagonal from the last element of the matrix:
>>> from sympy.abc import x, y, z >>> a = Matrix([x, y, z]) >>> b = Matrix([[1, 2], [3, 4]]) >>> c = Matrix([[5, 6]]) >>> diag(a, 7, b, c) Matrix([ [x, 0, 0, 0, 0, 0], [y, 0, 0, 0, 0, 0], [z, 0, 0, 0, 0, 0], [0, 7, 0, 0, 0, 0], [0, 0, 1, 2, 0, 0], [0, 0, 3, 4, 0, 0], [0, 0, 0, 0, 5, 6]])
When diagonal elements are lists, they will be treated as arguments to Matrix:
>>> diag([1, 2, 3], 4) Matrix([ [1, 0], [2, 0], [3, 0], [0, 4]]) >>> diag([[1, 2, 3]], 4) Matrix([ [1, 2, 3, 0], [0, 0, 0, 4]])
A given band off the diagonal can be made by padding with a vertical or horizontal "kerning" vector:
>>> hpad = ones(0, 2) >>> vpad = ones(2, 0) >>> diag(vpad, 1, 2, 3, hpad) + diag(hpad, 4, 5, 6, vpad) Matrix([ [0, 0, 4, 0, 0], [0, 0, 0, 5, 0], [1, 0, 0, 0, 6], [0, 2, 0, 0, 0], [0, 0, 3, 0, 0]])
The type is mutable by default but can be made immutable by setting the ``mutable`` flag to False:
>>> type(diag(1)) <class 'sympy.matrices.dense.MutableDenseMatrix'> >>> from sympy.matrices import ImmutableMatrix >>> type(diag(1, cls=ImmutableMatrix)) <class 'sympy.matrices.immutable.ImmutableMatrix'>
See Also ========
eye """
raise ValueError('unrecognized keyword%s: %s' % ( 's' if len(kwargs) > 1 else '', ', '.join(kwargs.keys()))) else: else:
""" Create matrix of Jordan cell kind:
Examples ========
>>> from sympy.matrices import jordan_cell >>> from sympy.abc import x >>> jordan_cell(x, 4) Matrix([ [x, 1, 0, 0], [0, x, 1, 0], [0, 0, x, 1], [0, 0, 0, x]]) """ n = as_int(n) out = zeros(n) for i in range(n - 1): out[i, i] = eigenval out[i, i + 1] = S.One out[n - 1, n - 1] = eigenval return out
"""Compute Hessian matrix for a function f wrt parameters in varlist which may be given as a sequence or a row/column vector. A list of constraints may optionally be given.
Examples ========
>>> from sympy import Function, hessian, pprint >>> from sympy.abc import x, y >>> f = Function('f')(x, y) >>> g1 = Function('g')(x, y) >>> g2 = x**2 + 3*y >>> pprint(hessian(f, (x, y), [g1, g2])) [ d d ] [ 0 0 --(g(x, y)) --(g(x, y)) ] [ dx dy ] [ ] [ 0 0 2*x 3 ] [ ] [ 2 2 ] [d d d ] [--(g(x, y)) 2*x ---(f(x, y)) -----(f(x, y))] [dx 2 dy dx ] [ dx ] [ ] [ 2 2 ] [d d d ] [--(g(x, y)) 3 -----(f(x, y)) ---(f(x, y)) ] [dy dy dx 2 ] [ dy ]
References ==========
http://en.wikipedia.org/wiki/Hessian_matrix
See Also ========
sympy.matrices.mutable.Matrix.jacobian wronskian """ # f is the expression representing a function f, return regular matrix else: # check differentiability raise ValueError("Function `f` (%s) is not differentiable" % f) # check differentiability raise ValueError("Function `f` (%s) is not differentiable" % f)
""" Apply the Gram-Schmidt process to a set of vectors.
see: http://en.wikipedia.org/wiki/Gram%E2%80%93Schmidt_process """ raise ValueError( "GramSchmidt: vector set not linearly independent")
""" Compute Wronskian for [] of functions
::
| f1 f2 ... fn | | f1' f2' ... fn' | | . . . . | W(f1, ..., fn) = | . . . . | | . . . . | | (n) (n) (n) | | D (f1) D (f2) ... D (fn) |
see: http://en.wikipedia.org/wiki/Wronskian
See Also ========
sympy.matrices.mutable.Matrix.jacobian hessian """
"""Given linear difference operator L of order 'k' and homogeneous equation Ly = 0 we want to compute kernel of L, which is a set of 'k' sequences: a(n), b(n), ... z(n).
Solutions of L are linearly independent iff their Casoratian, denoted as C(a, b, ..., z), do not vanish for n = 0.
Casoratian is defined by k x k determinant::
+ a(n) b(n) . . . z(n) + | a(n+1) b(n+1) . . . z(n+1) | | . . . . | | . . . . | | . . . . | + a(n+k-1) b(n+k-1) . . . z(n+k-1) +
It proves very useful in rsolve_hyper() where it is applied to a generating set of a recurrence to factor out linearly dependent solutions and return a basis:
>>> from sympy import Symbol, casoratian, factorial >>> n = Symbol('n', integer=True)
Exponential and factorial are linearly independent:
>>> casoratian([2**n, factorial(n)], n) != 0 True
"""
else:
"""Create random matrix with dimensions ``r`` x ``c``. If ``c`` is omitted the matrix will be square. If ``symmetric`` is True the matrix must be square. If ``percent`` is less than 100 then only approximately the given percentage of elements will be non-zero.
Examples ========
>>> from sympy.matrices import randMatrix >>> randMatrix(3) # doctest:+SKIP [25, 45, 27] [44, 54, 9] [23, 96, 46] >>> randMatrix(3, 2) # doctest:+SKIP [87, 29] [23, 37] [90, 26] >>> randMatrix(3, 3, 0, 2) # doctest:+SKIP [0, 2, 0] [2, 0, 1] [0, 0, 1] >>> randMatrix(3, symmetric=True) # doctest:+SKIP [85, 26, 29] [26, 71, 43] [29, 43, 57] >>> A = randMatrix(3, seed=1) >>> B = randMatrix(3, seed=2) >>> A == B # doctest:+SKIP False >>> A == randMatrix(3, seed=1) True >>> randMatrix(3, symmetric=True, percent=50) # doctest:+SKIP [0, 68, 43] [0, 68, 0] [0, 91, 34] """ else: 'For symmetric matrices, r must equal c, but %i != %i' % (r, c)) else: else: z = int(r*c*percent // 100) m._mat[:z] = [S.Zero]*z prng.shuffle(m._mat) return m |