Reputation: 23
I'm trying to convert a symbolic expression to an array in python.
For example, I have this symbolic expression:
import sympy as sp
import numpy as np
A,B = sp.symbols("A B")
G = 3*A**2*B - 2*A*B + A**2
What I want is to convert this to an array looking as follows:
[3*A**2*B,-2*A*B,A**2]
I know how to do this in Matlab, but I need to do it in Python as well.
What I've tried:
I've converted the symbolic expression to a polynomial, which allowed me to collect the coefficients.
C = G.as_poly().coeffs()
This gets me halfway there:
C = [3,-2,1]
But I want to have at least a similar list for all the variables.
Does anyone have an idea?
Upvotes: 2
Views: 202
Reputation: 28367
You can use as_ordered_terms
to get an ordered list of all the terms:
G.as_ordered_terms()
gives
[3*A**2*B, A**2, -2*A*B]
Alternatively, you can use args
to get all the top-level arguments of the object.
G.args
This will give a tuple:
(A**2, -2*A*B, 3*A**2*B)
Upvotes: 2