Matlab Quadratic equation -


struggling matlab quadratic equation. keep getting complex number answer , other errors keep occurring.

write matlab function solves quadratic equation of form a*x^2 + b*x + c = 0

the syntax of function should take form

[quadroots1,quadroots2] = q1_quadratic (a,b,c); 

where a, b , c quadratic coefficients; , quadroots1 , quadroots2 2 determined roots. case 1 root present (for example when a=1, b=2 , c=1), should set second output nan (not number). if no roots present, set both outputs nan.

make sure check if number under root sign in quadratic formula is:

  • positive (>0): 2 distinct real roots,
  • equal 0 (==0): single real numbered degenerate root (or, rather, 2 non-distinct roots).
  • negative (<0: roots complex (recall sqrt(-1) = i, our imaginary unit i). sound of question specs, seems treat complex if "no roots present".

you can check cases above in function q1_quadratic(...) using if-elseif-else clause, e.g.:

function [quadroots1, quadroots2] = q1_quadratic(a, b, c)    d = b^2 - 4*a*c; % number under root sign in quad. formula    % real numbered distinct roots?   if d > 0     quadroots1 = (-b+sqrt(d))/(2*a);     quadroots2 = (-b-sqrt(d))/(2*a);   % real numbered degenerate root?   elseif d == 0      quadroots1 = -b/(2*a);     quadroots2 = nan;   % complex roots, return nan, nan   else     quadroots1 = nan;     quadroots2 = nan;   end     end 

test:

% distinct real roots: expects [2, -8] [a, b] = q1_quadratic(1, 6, -16)     % ok!  % degenerate real root: expects [-1, nan] [a, b] = q1_quadratic(1, 2, 1)     % ok!  % complex roots: expects [nan, nan] [a, b] = q1_quadratic(2, 2, 1)     % ok! 

Comments

Popular posts from this blog

c++ - llvm function pass ReplaceInstWithInst malloc -

Cross-Compiling Linux Kernel for Raspberry Pi - ${CCPREFIX}gcc -v does not work -

java.lang.NoClassDefFoundError When Creating New Android Project -