# Extract coefficients from ODE

I'm trying to extract the coefficients from an ODE $$y''''+y''+x^2 y'-6y+ 8\ cos(x)$$
and hoping the code will give a list with all the coefficients in, ranging from lower order to higher order, i.e. $$\{8\ cos(x)\,,\,-6y\,,\,x^2\,,\, 1\,,\,1\}$$

So far I can only extract the $$x^2$$ and $$-6$$ in $$x^2 y'$$ and $$-6y$$ using

In[1] : Cases[ y'''' + y'' + x^2 y' - 6 y + 8 Cos[x],
Times[x_, Derivative[_][_]] :> x, Infinity]
Out[2]: {x^2}

In[3] : Cases[ y'''' + y' + x^2 y' - 6 y + 8 Cos[x], x__ y :> x, Infinity]
Out[4]: {-6}

How can I deal with the $$y'''$$ and $$y''$$ which do not have the Times header before them? I've tried this one which just return me all the $$y^{(n)}$$s.

In[5]: Cases[ y'''' + y'' + x^2 y' - 6 y + 8 Cos[x],
Derivative[_][y], Infinity]
Out[6]: {y',y'',y''''}
• not very clean but it works: CoefficientList[expression /. y -> (Exp[α #] &) /. (q_. Exp[α #] &) -> q, α] or CoefficientList[expression /. y -> (Exp[α #] &) /. Function[q_] -> q Exp[-α] /. Slot[_] -> 1, α]. I'm sure there are better ways though. – AccidentalFourierTransform Nov 24 '19 at 2:52

Given that it's linear, I would probably do it this way:

CoefficientList[
y'''' + y'' + x^2 y' - 6 y + 8 Cos[x] /.
Derivative[n_][y] :> y^(n + 1), {y}]
(*  {8 Cos[x], -6, x^2, 1, 0, 1}  *)

Note that the output here has the coefficient of y''', which the desired output in the OP omits. I see every reason to include it, though.

More straightforward:

Flatten@CoefficientArrays[y'''' + y'' + x^2 y' - 6 y + 8 Cos[x],
Table[Derivative[n][y], {n, 0, 4}]]
(*  {8 Cos[x], -6, x^2, 1, 0, 1}  *)
• But the code will confuse between y and y'.... – WeiShan Ng Nov 24 '19 at 5:12
• @WeiShanNg Oops. make it n+1. – Michael E2 Nov 24 '19 at 13:50