Discover MakerZone

MATLAB and Simulink resources for Arduino, LEGO, and Raspberry Pi

Learn more

Discover what MATLAB® can do for your career.

Opportunities for recent engineering grads.

Apply Today

how to solve quadratic equation?

Asked by bsd on 8 Nov 2011

Hai,

How could I solve a quadratic equation in matlab? Looking for your reply.

BSD

0 Comments

bsd

Products

No products are associated with this question.

2 Answers

Answer by Walter Roberson on 8 Nov 2011
Accepted answer
roots(). Or if you have the symbolic toolbox, solve()

4 Comments

Walter Roberson on 8 Nov 2011

And note that any root that is output might be complex. If you want only the real roots, filter to TheRoots(imag(TheRoots)==0)

bsd on 9 Nov 2011

why is that == 0 used?

BSD

Walter Roberson on 9 Nov 2011

You can tell whether a number has a complex part or not by testing to see if the imaginary part is 0. imag(x) gives you the imaginary part of x, so imag(x)==0 tests whether the imaginary part is 0. TheRoots(imag(TheRoots)==0) thus selects only the roots which are real-valued with no imaginary component.

Of course for a quadratic function over real coefficients, either _neither_ root is complex or _both_ roots are complex...

Walter Roberson
Answer by Rick Rosson on 8 Nov 2011

Please try:

   x = zeros(2,1);
   d = sqrt(b^2 - 4*a*c);
   x(1) = ( -b + d ) / (2*a);
   x(2) = ( -b - d ) / (2*a);

HTH.

Rick

4 Comments

Walter Roberson on 9 Nov 2011

Beware a = 0 !

Rick Rosson on 9 Nov 2011

If a = 0, then it is not (strictly speaking) a quadratic equation. It's a linear equation, and the solution in that case is trivial to compute.

Walter Roberson on 9 Nov 2011

Yes, but it is not an uncommon problem for people to calculate or randomly generate the coefficients and forget to double-check that the system is still of the same order.

Rick Rosson

Contact us