I'm attempting to implement the variation of parameters method of solving a linear nonhomogeneous ODE (as a coding problem to help learn Mathematica). As a first step, I would like to form the characteristic equation of my ODE function.

My test ODE is:

f[x_, y_] := y'' + 3 y' - 2 y - Sin[E^-x]

Which has the characteristic equation:

s^2 + 3s - 2 = 0

My naive attempt at getting the characteristic equation is:

variationOfParameters[fun_] := 
 Plus @@ Cases[fun[x, y], _.*y | _.*_Derivative[y]] /. {yPrime :_Derivative[y] -> 
    Position[FullForm[yPrime], _Integer]], y -> 1}

The Cases part works, the ReplaceAll however does not (output is an empty list). But when I test the rule manually it produces the correct answer, e.g.

 Position[FullForm[y''], _Integer]]

What am I doing wrong? Additionally if you have any advice on making this function better, I would be happy to hear it.

Thank you.


3 Answers 3


I think this does what you want:

Select[f[x, y], Not@*FreeQ[y]] /. Derivative[n_][y] :> s^n /. y -> 1
-2 + 3 s + s^2

More obfuscated, but fun to write:

Tr @ Cases[f[x, y], x_. (Derivative[n_][y] | y) :> Last[x s^{0, n}]]
-2 + 3 s + s^2
  • $\begingroup$ Wow this is beautiful and clean, thanks! $\endgroup$
    – loup-garou
    Commented Aug 27, 2017 at 5:57
  • $\begingroup$ @user3547456 You're welcome; I'm glad you like it. $\endgroup$
    – Mr.Wizard
    Commented Aug 27, 2017 at 6:04

I would like to form the characteristic equation of my ODE function.

to get the characteristic equation, which applies only to the homogeneous part of the ode, you can use the following LaplaceTransform trick

odeH=y''[t]+3 y'[t]-2 y[t]==0;
charEq= lap/.{LaplaceTransform[y[t],t,s]->1,y[0]->0,y'[0]->0}

Mathematica graphics

  • $\begingroup$ Thanks for this trick! But I should have said my intent was more to learn about pattern matching in Mathematica. $\endgroup$
    – loup-garou
    Commented Aug 27, 2017 at 4:41

I figured out a much simpler solution,

variationOfParameters[fun_] := 
 Plus @@ Cases[
    f[x, y], _.*y | _.*_Derivative[y]] /. {Derivative[orders_][y] -> 
    s^orders, y -> 1}

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.