2

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?

1 Answer 1

2

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)
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.