I'm calculating the roots of a polynomial like B= Roots[A==0,y] where A is the characteristic polynomial of a matrix of interest. This returns equations like:


y == ...


y == ...

I'd like to use the roots as functions to derivate, plot and do stuff but B already is an equation like y== [an expression]. I'd like to use that expression as a function to plot it, etc. How can I do it?

For example, if the polynomial were x^2 -a then B would be:





Now, I want to define a function like f[a_]:=B[[1]] but that obviusly doesn't work since B is an equation an not the expression.

  • 2
    $\begingroup$ Please give a concrete but minimal example. $\endgroup$ – David G. Stork May 4 '17 at 22:17
  • $\begingroup$ I add something at the end... does it help? $\endgroup$ – P. C. Spaniel May 4 '17 at 22:28
  • $\begingroup$ Do you want f[a_] or f[x_]? $\endgroup$ – David G. Stork May 4 '17 at 22:32
  • $\begingroup$ f[a_]... The roots are written in terms of symbolic variables and I want to use them as functions. But roots gives back equations, not expressions. $\endgroup$ – P. C. Spaniel May 4 '17 at 22:34
  • 1
    $\begingroup$ Possible duplicate of Assign the results from a Solve to variable(s) $\endgroup$ – Artes May 4 '17 at 22:48

When we look at what Roots returns with FullForm (which shows an expression the way a Mathematica evaluator "sees" it, we get, for example,

Roots[x^2 - a == 0, x] // FullForm
  Equal[x, Times[Power[-1, Rational[2, 3]], Power[a, Rational[1, 3]]]],  
  Equal[x, Times[-1, Power[-1, Rational[1, 3]], Power[a, Rational[1, 3]]]], 
  Equal[x, Power[a, Rational[1, 3]]]]

Were we to change the head Or to List, we would have a simple list of Equal expressions. From these we could extract the 2nd argument with Part (which works with any head, not just List) and get the expressions you want.

Here is the code that does what is described above.

 (List @@ Roots[x^3 - a == 0, x])[[All, 2]]

{(-1)^(2/3) a^(1/3), -(-1)^(1/3) a^(1/3), a^(1/3)}


To make a Function out of an equation y == f[x1, x2,...]:

makeFunction /: makeFunction == expr_ := Function @@ {Variables@expr, expr};
List @@ Roots[a x^2 + b x + c == 0, x, EquatedTo -> makeFunction]
  {Function[{a, b, c}, (-b - Sqrt[b^2 - 4 a c])/(2 a)], 
   Function[{a, b, c}, (-b + Sqrt[b^2 - 4 a c])/(2 a)]}

The variables will be sorted into canonical order by Variables.


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