7
$\begingroup$

In Maple I often simplify expressions for functions of same argument using the collect command:

> collect(a*f(x)+f(y)+x*f(x), f, factor)
(a+x)*f(x)+f(y)

where the extra option factor will factor the coefficients.

In contrast Mathematica:

> Collect[a*f[x] + f[y] + x*f[x], f]
a f[x] + x f[x] + f[y]

Is there some command in Mathematica which achieves the same?

$\endgroup$

1 Answer 1

15
$\begingroup$

You need to use a pattern in Collect which will match the terms you are trying to collect. In this case we want to collect terms like f[x] and f[y] so a suitable pattern is _f which matches any expression with head f:

Collect[a*f[x] + f[y] + x*f[x], _f]
(* (a + x) f[x] + f[y] *)
$\endgroup$
3
  • $\begingroup$ Is there also a way to act a routine on the coefficients of the collected terms, like the factor in the Maple command? $\endgroup$
    – highsciguy
    Commented Dec 18, 2013 at 22:18
  • $\begingroup$ @highsciguy, Collect takes a third argument which is a function to be applied to each coefficient. $\endgroup$ Commented Dec 18, 2013 at 22:20
  • $\begingroup$ @SimonWoods I wonder is there is any general explanation so one don't have to try in each case for collect. I mean, Head of Derivative[1, 2][w][r,t] is Derivative[1, 2][w] but Derivative[__][w] is not enough for Collect and one has to do Collect[b D[w[r, t], r] + a D[w[r, t], r], Derivative[__][w][r, t]] $\endgroup$
    – Kuba
    Commented Apr 8, 2014 at 7:38

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.