Automatically populate matrix elements in SymPy

Is there a way to implicitly define elements of a symbolic matrix in SymPy by following a rule, for example: symbol , and then a subindex in a matrix (or a pair of numbers)

For example, I would like to define a 3 x 2 matrix called M , and I would like Sympy to automatically create it and populate it as:

 M = [ M_11 M_12] [ M_21 M_22] [ M_31 M_32] 

If there is no way to do this implicitly, what would be the easiest way to do it explicitly (e.g. a loop)?

+7
source share
2 answers

How about something like this:

 import sympy M = sympy.Matrix(3, 2, lambda i,j:sympy.var('M_%d%d' % (i+1,j+1))) 

Edit: I guess I should add a little explanation. The first two arguments to sympy.Matrix () define the matrix as 3x2 (as you indicated). The third argument is the lambda function, which is essentially a shorthand way to define a function on a single line, rather than formally defining it with def . This function takes as input the variables i and j , which are conveniently matrix indices. For each pair (i, j) that are passed to lambda (i.e., for each element of the matrix), we create a new symbolic variable M_ij . sympy.var () takes a string as input that defines the name of a new symbolic variable. We generate this line "on the fly", using the format string "M_% d% d" and filling it (i + 1, j + 1) . We add 1 to i and j , because you want the matrix to be 1-indexed, not 0-indexed, like the standard in Python.

+11
source

Consider using a MatrixSymbol object rather than a Matrix . MatrixSymbol represents matrices without the need for explicit elements.

 In [1]: M = MatrixSymbol('M', 3, 2) In [2]: M # Just an expression Out[2]: M In [3]: Matrix(M) # Turn it into an explicit matrix if you desire Out[3]: ⎡M₀₀ M₀₁⎤ ⎢ ⎥ ⎢M₁₀ M₁₁⎥ ⎢ ⎥ ⎣M₂₀ M₂₁⎦ In [4]: MT * M # Still just an expression Out[4]: TM ⋅M In [5]: Matrix(MT * M) # Fully evaluate Out[5]: ⎡ 2 2 2 ⎤ ⎢ M₀₀ + M₁₀ + M₂₀ M₀₀⋅M₀₁ + M₁₀⋅M₁₁ + M₂₀⋅M₂₁⎥ ⎢ ⎥ ⎢ 2 2 2 ⎥ ⎣M₀₁⋅M₀₀ + M₁₁⋅M₁₀ + M₂₁⋅M₂₀ M₀₁ + M₁₁ + M₂₁ ⎦ 
+15
source

All Articles