MATLAB: Real Roots of a Polynomial

MATLABsolve

I have used "solve" to factor a fourth order polynomial. It has four roots with three complex numbers. I used:
xf = solve(x^4+7*x^3-8*x^2+5*x+2,x)
if (isreal(xf)==1)
...
end;
to try to pull out the real roots but it did not work.
Is there a better way?

Best Answer

Use 'roots' to find the roots of polynomials.
r = roots([1,7,-8,5,1]); % Get all the roots
r = r(imag(r)==0); % Save only the real roots
The 'isreal' function is true only if All elements of a vector are real, so it isn't appropriate for sorting out the real roots.
A polynomial with all real coefficients such as yours cannot have an odd number of complex roots. They must occur in conjugate pairs. As you see, in your particular polynomial there are just two complex roots, which are conjugates of one another.