function x = quadraticformula(a, b, c)
%QUADRATICFORMULA Finds roots of quadratic equation specified by the real 
%   scalar input values a, b, c (a ~=0 ) and outputs a vector 
%   x = [x(1); x(2)] of real or complex values that are the roots of the 
%   quadratic polynomial 
%
%                       a*x^2 + b*x + c = 0. 
%
%   This program utilizes the elementary quadratic formula.
%
% Inputs:
%    a      real leading coefficient of quadratic polynomial. This
%           coefficient must not be zero.
%
%           -or- a vector of length 3 whose elements are the 
%           coefficients (in descending powers) of an 2nd-degree
%           polynomial.
%
%    b      real linear coefficient of a quadratic polynomial.
%
%    c      real constant term of a quadratic polynomial. 
%
%           The inputs should form the 2nd degree polynomial ax^2 + bx + c
%
% Outputs:
%    x      A 2 x 1 vector of roots of the input 2nd degree polynomial.
%
% Example: 
%   x = quadraticformula(1,1,1)
%   Result:
%   x =
%     -0.5000 + 0.8660i
%     -0.5000 - 0.8660i
%
%   x = quadraticformula([1 1 1])
%   Result:
%   x =
%     -0.5000 + 0.8660i
%     -0.5000 - 0.8660i
%
% Other m-files required: none
% Subfunctions: none
% MAT-files required: none
%
% See also: polyval, isreal, isnumeric, zeros, error, sprintf
%           
% Author: 451 Instructor
% Work Address
% email: 
% Website: http://www.
% First Version: 09/01/2020
% Last Modified: 09/01/2020
%
%------------- BEGIN CODE --------------

    % Initialize the output variable to a default value that indicates and
    % error was encounteredd before the roots could be computed.
    x = nan(2,1);

    if nargin == 1
        b = a(2);
        c = a(3);
        a = a(1);
    end
    
    % Inputs should be numbers only
    if ~all(isnumeric([a b c]))
        error('%s: %s. %s', ...
              'Error', 'Invalid expression', ...
              'The input values must be real scalars.')
          
    % Inputs should be real numbers (no complex polynomials!)
    elseif ~all(isreal([a b c]))
        error('%s: %s. %s', ...
              'Error', 'Invalid expression', ...
              'The input values must be real valued.')

    % Compute the two roots
    else
        
        if abs(a) > eps
            % Compute the discriminant once because it is required to
            % determine both roots.
            discriminant = sqrt(b^2 - 4*a*c);

            % Calculate the two roots and assign the values to the vector x
            x = (-b + [ discriminant; -discriminant ])./(2*a);
        end
    end
end

%------------- END OF CODE --------------
%Please send suggestions for improvement of the above template header 
%to Denis Gilbert at this email address: gilbertd@dfo-mpo.gc.ca.
%Your contribution towards improving this template will be acknowledged in
%the "Changes" section of the TEMPLATE_HEADER web page on the Matlab
%Central File Exchange
