OverseasGriffo
OverseasGriffo

Reputation: 11

Matlab Quadratic equation

Struggling with a MATLAB quadratic equation. I keep getting a complex number as my answer and other errors keep occurring.

Write a MATLAB function that solves a quadratic equation of the form a*x^2 + b*x + c = 0

The syntax of your function should take the form

[quadRoots1,quadRoots2] = Q1_quadratic (a,b,c);

where a, b and c are the quadratic coefficients; and quadRoots1 and quadRoots2 are the two determined roots. For the case where only one root is present (for example when a=1, b=2 and c=1), you should set your second output to NaN (not a number). If no roots are present, then set both outputs to NaN.

Upvotes: 0

Views: 9804

Answers (1)

dfrib
dfrib

Reputation: 73206

Make sure to check if the number under the root sign in your quadratic formula is:

  • Positive (>0): two distinct real roots,
  • Equal to zero (==0): single real numbered degenerate root (or, rather, two non-distinct roots).
  • Negative (<0: your roots are complex (recall sqrt(-1) = i, with our imaginary unit i). From the sound of your question specs, it seems you are to treat complex as if "no roots are present".

You can check the cases above in your function Q1_quadratic(...) using an if-elseif-else clause, e.g.:

function [quadRoots1, quadRoots2] = Q1_quadratic(a, b, c)

  d = b^2 - 4*a*c; % your number under the 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!

Upvotes: 1

Related Questions