- Save the function as quadroot.m in different Matlab file.
- Call the function by passing inputs arguments from another main Matlab scripts or from command window (as shown)
Info
This question is closed. Reopen it to edit or answer.
I'm having trouble getting my first Matlab code to work? Can anyone tell me what's wrong?
1 view (last 30 days)
Show older comments
function [x1,x2,errflag] = quadroot(a,b,c)
if (a == 0)
error('\nThis equation is not quadratic\n')
elseif (a ~= 0)
max_num = max(max(abs(a),abs(b)),abs(c));
if (max_num ~= 0)
m=(1/max_num);
a=m*a;
b=m*b;
c=m*c;
else
error('\nAll coefficients zero\n')
end
D=b^2-4*a*c;
if (D<0)
x1=-b/(2*a);
x2=(sqrt(-D))/(2*a);
errflag=('x1 is real part, x2 is imaginary part of compex pair');
elseif (b<0)
x1=(-b+sqrt(D))/(2*a);
x2=(c/a*x1);
errflag=('x1 and x2 are real roots');
else
x1=(-b-sqrt(D))/(2*a);
x2=(c/a*x1);
errflag=('x1 and x2 are real roots');
end
end
end
0 Comments
Answers (1)
KALYAN ACHARJYA
on 27 Sep 2019
Edited: KALYAN ACHARJYA
on 27 Sep 2019
2 Comments
KALYAN ACHARJYA
on 27 Sep 2019
Edited: KALYAN ACHARJYA
on 27 Sep 2019
If you pass the a=0, then the equation is not quadratic, it not error, it notify the user by forllowing line in the code:
if (a == 0)
error('\nThis equation is not quadratic\n')
When you pass a=0 to the function, it display the above message
See Also
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!