Use MATLAB write the following code The roots of a quadratic equation ax 2 + bx
ID: 3938210 • Letter: U
Question
Use MATLAB write the following code
The roots of a quadratic equation ax2 + bx +c = 0 are given by the formula
x= (-b ± (b^2 - 4 ac^ ))/2a (quadratic fromula)
In MATLAB Write a function that take as input the coefficients a,b,c and returns as output the roots x1,x2 of the quadratic equation. Let x1 be the smaller of the two roots.
If a is zero, print a warning message informing the user of the situation. Then solve the linear equation for the single root x1 and set x2= NaN
If b2-4ac is negative, print a warning message informing the user of the situation. Then solve the equation anyways to find and return the complex roots.
If b2-4ac is zero, set x2=x1=-b/2a
If any of a,b,c are not scalar numbers, print an error message informing the user of the situation and set x1=x2=NaN
Explanation / Answer
function[x1,x2]=root[a,b,c]
if a == 0
% if condition is true then print the following
fprintf('Value of a is 0 ' );
x1=(-c/a);
x2=NaN;
elseif( (b^2 - 4*a*c) < 0 )
% if else if condition is true
fprintf('Value of negative, return complex root ' );
p=[a b c];
r=root[p];
elseif ((b^2 - 4*a*c) == 0 )
% if else if condition is true
fprintf('Value are Zero.So root are same ' );
x1=(-b/2a);
x2= x1;
else
% if none of the conditions is true '
fprintf('None of the values are matching ');
fprintf('Exact value of a is: %d ', a );
end
END
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.