Question
matlab
If a second order polynomial is written in the general form: ax^2 + bx + c = 0 then the roots (i.e. the values of x that satisfy the equation) can be determined using the quadratic formula: x = -b plusminus Squarerootb^2 - 4ac/2a The test suite workspace includes a vector variable abc that is a 3-element row vector with values for a, b, and c in the first second, and third column respectively. Write a script fade to do the following: Check if the roots are real and distinct. Note that the roots will be real if the value under the squareroot is greater that an or equal to zero. They will not be distinct however, if the value under the squareroot is exactly equate to zero. Create an integer variable root condition and assign it a value as follows: The value 2 if the roots are real and distinct The value 1 if the two roots are the same. The value o if the roots are not real (i.e. complex because the value under the squareroot is less than 0) In cases where there are two real and distinct roots, compute the two roots and assign them in ascending order to a two element row vector x solution. In cases where the two roots are the same, solve for the root and assign to a scalar variable x_ solution. Do not create the variable x_solution it the roots are complex.
Explanation / Answer
%%quadraticRoot.m
%%The matlab script file that takes three scalar values
%%and finds the roots of a quadratic equation.
function quadraticRoot(a,b,c)
%%calculate descrimination value
delta=sqrt(b*b-4*a*c);
%%two real and distinct roots
if delta>0
rootConditon=2;
%%imaginary roots
elseif delta==0
rootConditon=1;
else
%%no real roots
rootConditon=1;
end
%%calculate real roots for root condition=2
if rootConditon==2
x_solution(1)=(-1*b+delta)/(2*a)
x_solution(2)=(-1*b-delta)/(2*a)
%%calculate real roots for root condition=1
elseif rootConditon==1
x_solution(1)=-b/(2*a)
else
%%display No solutin
disp('No solution');
end