I have the following equation,

 equation= x''[t]+a*x'[t]+b*x[t]+c*y[t]+d*u[t]+e*v[t]+Sum[f[i]*x[t]+g[i]*u[t]+h[i],{i,1,n}]+k

When I collect the coefficient of each x[t] derivatives, x[t],y[t], u[t] and v[t] the correct answer should be

 { 1,a,b+sum[f[i],{i,1,n}],c,d+sum[g[i],{i,1,n}],e,k+sum[h[i],{i,1,n}]} 

However when I use Coefficient[] function for each variable, I can get answer mostly correct except that I am not getting b+sum, d+sum, and k+sum. This is because Collect function is unable to separate sum from x[t],u[t] and constant. Is it possible to separate sum from variable[t]? How to collect coefficient that has summation formula?


2 Answers 2


Adapting this answer and that answer, and still assuming a linear ODE:

linearExpand[e_, x_, head_] := 
  e //. {op : head[arg_Plus, __] :> Distribute[op], 
    head[arg1_Times, rest__] :> 
     With[{dependencies = 
        Internal`DependsOnQ[#, x] & /@ List @@ arg1}, 
      Pick[arg1, dependencies, False] head[
        Pick[arg1, dependencies, True], rest]]};

 linearExpand[equation, x, Sum] /. 
  Derivative[n_][x][t] :> x[t]^(n + 1), {x[t]}]
  {k + n - HarmonicNumber[n] - StieltjesGamma[1] + 
    StieltjesGamma[1, 1 + n] + d u[t] + n u[t] - 
    HarmonicNumber[n] u[t] + e v[t] + c y[t],
   b + n f[i],

Note that when the sum is split up, Sum can evaluate the sum of each term.


You can tell Mathematica to expand sums before asking it to collect terms. Collect and Coefficient and friends are meant for explicit polynomials, but are nonetheless useful. Consider


and the less pretty

        If[{}==Cases[a,{range}[[1]],Infinity],a Sum[b,{range}],
        If[{}==Cases[b,{range}[[1]],Infinity],b Sum[a,{range}],

The latter rule needs to check if one of the multiplicands of the expression being summed is independent of the summation variable (we can only factor out constants). It doesn't work for indefinite sums. It does work, however, in this case:


yields {b+Sum[f[i],{i,1,n}]}.


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.