# collect multiple variables and simplify their coefficients

Hi there!

In Mathematica you can do the following: Collect[expr, {var1, var2, var3}, Simplify]

This transforms

expr = var1expr11 + var2expr22 + var1var2expr12 + ...

to

var1Simplify[expr11] + var2Simplify[expr22] + var1var2Simplify[expr12] + ...

I was wondering if there is an easy way to do this in Sage.

So my questions are:

1) How can you collect multiple variables?

2) How can you manipulate their coefficients? (each coefficient is independent)

3*) How can you print the result in a pretty way? (e.g. collecting the expression by coefficients and printing each term in a new line)

Thanks for your help!

edit retag close merge delete

Sort by ยป oldest newest most voted

Here are two helpful functions:

sage: var('x,y,z')
(x, y, z)
sage: expr=x^2*y+2*x*y*z+54*z-3*x*z
sage: expr.collect(x)
x^2*y + (2*y*z - 3*z)*x + 54*z
sage: expr.coefficients(x)
[[54*z, 0], [2*y*z - 3*z, 1], [y, 2]]

more

Okay, thank you! It seems I have to do it manually then.

( 2011-10-10 01:02:21 -0600 )edit

maxima allows to collect multiple terms, so it is possible to do so in Sage using:

sage: f = 4*x*y + x*z + 20*y^2 + 21*y*z + 4*z^2 + x^2*y^2*z^2
sage: fm = f.maxima_methods()
sage: fm.collectterms(x,y)
x^2*y^2*z^2 + 4*x*y + x*z + 20*y^2 + 21*y*z + 4*z^2
sage: fm.collectterms(x)
x^2*y^2*z^2 + (4*y + z)*x + 20*y^2 + 21*y*z + 4*z^2


from there you could use the operands() method to simplify each term separately. Is this enough?

Can you assume that your expression is polynomial in x and y?

more