This algorithm finds the roots of a quadratic equation in the form ax^2 + bx + c = 0.It tests for several conditions:

-If a = 0 and b = 0, then the equation reduces to c = 0. If this condition occurs we call the equation degenarete.

-If a = 0 and b ~= 0, the equation reduces to bx + c = 0 with single root at -c/b.

-If a ~= 0 and c = 0, the equation reduces to ax^2 + bx = 0. There are two roots, 0 and -b/a.

-If none apply we use the famous equation to find roots. Roots are either complex or real depending on the discriminant.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 |
%Quadratic Equation Solver in MATLAB array=input('Specify the coefficients of the quadratic as a row array "[a,b,c]":'); a=array(1); b=array(2); c=array(3); if (a==0) && (b==0) fprintf('The equation is degenerate'); end if (a==0) && (b~=0) fprintf('There is a single root at %g.\n', -c/b); end if (a~=0) && (c==0) fprintf('There are two real roots at 0 and %g.\n', -b/a); end if (a~=0) && (c~=0) root1=((-b+sqrt(b*b-4*a*c))/(2*a)); root2=((-b-sqrt(b*b-4*a*c))/(2*a)); if isreal(root1) fprintf('There are two real roots at %g and %g.\n.', root1, root2); else fprintf('The roots are complex:\n'); fprintf(' '); disp(root1); fprintf(' and '); disp(root2); end end |

Pingback: MATLAB postings review | CroAxis.com

Hi,

A pair of brackets is missing in the following two equations:

root1=(-b+sqrt(b*b-4*a*c)/(2*a));

root2=(-b-sqrt(b*b-4*a*c)/(2*a));

For instance, try giving the input as [a b c]=[1 4 4]. The program will return -4 and -4 as the roots.

Whereas the actual roots are: -2 and -2. So, the equations should have been as below-

root1=((-b+sqrt(b*b-4*a*c))/(2*a));

root2=((-b-sqrt(b*b-4*a*c))/(2*a));

Instead of all this code, Use :

exp = ‘x^2 + 3*x + 2’ ; % put any expression u need to evaluate

solve ( exp )

This is the advantage of Matlab ðŸ™‚

In no other language can you do it…

Check this one for a better approach: http://www.javaist.com/blog/2012/06/19/finding-roots-of-polynomials-in-matlab/

exp = â€˜x^2 + 3*x + 2â€² ; % put any expression u need to evaluate

solve ( exp )

if I use the above command Matlab asks me that what unefined variable x. So in that case what should I do??

Thanks dude!

what if i want to plot a graph for the quadratic equation and trace its roots onn the graph? how do i go about that?

To plot a polynomial: (as an example)

To designate the roots (if there are any) on the plot, you can use:

where fzero returns the roots as (x,y) pairs.