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)
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

Answers (1)

KALYAN ACHARJYA
KALYAN ACHARJYA on 27 Sep 2019
Edited: KALYAN ACHARJYA on 27 Sep 2019
  1. Save the function as quadroot.m in different Matlab file.
  2. Call the function by passing inputs arguments from another main Matlab scripts or from command window (as shown)
  2 Comments
Amanda McGovern
Amanda McGovern on 27 Sep 2019
Thank you but is there something wrong in the code that could explain why it's not working. i get an error regarding if (a == 0) but am not sure why.
KALYAN ACHARJYA
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

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!