Message Boards Message Boards

0
|
5820 Views
|
7 Replies
|
1 Total Likes
View groups...
Share
Share this post:

Desired behavior of Collect[]

I need the following behavior of Collect[] or other Formula Manipulation function, when

Collect[a*x+b*x+c*x^2+d*x^2, x^2]

would return

a*x+b*x+(c+d)*x^2

i.e. the function collects summands with a specified power of x. It's clear, the problem can be solve by applying x^2 -> z, Collect[..., z], z -> x^2, but it is desirable to find straightforward way.

POSTED BY: Konstantin Nosov
7 Replies

This is a naive string manipulation, but it works OK for positive integer powers.

    newTerm[a_,b_]:=ToExpression[(a//ToString)<>"¢"<>(b//ToString)]

    collect[expr_,{vars__}]:=StringReplace[ToString[Collect[expr/.Power->newTerm,Flatten[{{vars}/.Power->newTerm}]]],"¢"->"^"]//ToExpression

    collect[expr_,vars_]:=StringReplace[ToString[Collect[expr/.Power->newTerm,Flatten[{{vars}/.Power->newTerm}]]],"¢"->"^"]//ToExpression

For example:

In[179]:= collect[a x+b x+c x^2+d x^2+e y + f y+g y^2+h y^2,{x^2,y^2,x}]
Out[179]= (a+b) x+(c+d) x^2+e y+f y+(g+h) y^2

or, with x^2 y collected:

In[180]:= collect[a x+b x+c x^2 y+d x^2 y+e y + f y+g y^2+h y^2,{x^2 y,y^2,x}]
Out[180]= (a+b) x+e y+f y+(c+d) x^2 y+(g+h) y^2

or, with only one term to collect, the braces are not needed:

In[211]:= collect[a x^2+b x+c x^2+d x,x^2]
Out[211]= b x+d x+(a+c) x^2
POSTED BY: Eric Johnstone

removed

POSTED BY: Eric Johnstone

With more variable you have to decide how to deal with mixed terms x1*x2

POSTED BY: Gianluca Gorni

Sorry, I had to clarify this issue. The second-order terms specified in the command should be collected as usual:

Collect[..., x1^2, x2^2, x1*x2, ...]
POSTED BY: Konstantin Nosov

A similar problem was discussed in the thread "How to Get a Taylor Series for Multiple Variables?".

POSTED BY: Gianluca Gorni

I don't know if this is straightforward enough

Collect[a*x + b*x + c*x^2 + d*x^2, x] /. coeff_*x :> Expand[coeff*x]
POSTED BY: Gianluca Gorni

Thank you, enough straightforward. Can the code be extended for expression with several variables (i.e., x1^2, x2^2, ..., xn^2)?

POSTED BY: Konstantin Nosov
Reply to this discussion
Community posts can be styled and formatted using the Markdown syntax.
Reply Preview
Attachments
Remove
or Discard

Group Abstract Group Abstract