Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create symbolic matrix and do substitute in batch with sympy?

I need to create completely symbolic matrices, are there ready made functions for that in sympy?

For example, if I were to create a 2x2 matrix manually, I would do

from sympy import *

a00, a01, a10, a11 = symbols('a00 a01 a10 a11')
A = Matrix([[a00, a01],[a10, a11]])

The problem is I do not know the dimension prior to simulation and creating every symbol manually gets old fast when dimension gets higher. Ideally I want to be able to create a 10x10 matrix with A=Matrix(10,10) with A[0,0]=Symbol('A00'), etc.

Also, if the above is possible, it'd be really nice to be able to do substitution in batch as well. For example, I want something like some_equation.subs([(A,numpy.random.rand(2,2))])

like image 561
lingxiao Avatar asked Oct 06 '15 03:10

lingxiao


People also ask

How do you substitute values in SymPy?

The subs() function in SymPy replaces all occurrences of first parameter with second. This function is useful if we want to evaluate a certain expression. For example, we want to calculate values of following expression by substituting a with 5.

How do you write an ex in SymPy?

Note that by default in SymPy the base of the natural logarithm is E (capital E ). That is, exp(x) is the same as E**x .

Is SymPy a NumPy?

Relationship with NumPy: NumPy and SymPy are both libraries that can deal with mathematics. However, they are fundamentally different! NumPy operates numerically, while SymPy works with symbolic expressions. There are both advantages and disadvantages to both approaches.


2 Answers

You can use subs method to do the substitution.

In [5]: A = MatrixSymbol('A', 2, 2)

In [6]: B = MatrixSymbol('B', 2, 2)

In [7]: C = A*B

In [8]: C.subs({A: Matrix([[0, 1], [1, 0]]), B: Matrix([[2, 3], [4, 5]])})
Out[8]: 
Matrix([
[0, 1],
[1, 0]])*Matrix([
[2, 3],
[4, 5]])

Probably you need symbolic dimension for your MatrixSymbol objects.

like image 78
Sudhanshu Mishra Avatar answered Oct 13 '22 17:10

Sudhanshu Mishra


I think you might have been trying to make all the elments of a matrix separate symbols? Here's something I tried to make an array rho that is "states x states" in size:

rho = np.array([[Symbol("rho{}{}".format(i,j)) for j in range(len(states))] for i in range(len(states))])
like image 34
Ashwin Singh Avatar answered Oct 13 '22 16:10

Ashwin Singh