function that returns the number of real roots of a quadratic in matlab

To create a function in MATLAB that calculates the number of real roots of a quadratic equation, one approach is to use the discriminant. The discriminant is the expression under the square root sign in the quadratic formula, b^2 - 4ac. The number of real solutions depends on the sign of the discriminant.

Here's an example function:

main.m
function num_roots = num_real_roots(a, b, c)
% Given coefficients a, b, and c of a quadratic equation
% returns the number of real roots

% calculate discriminant
D = b^2 - 4*a*c;

if D > 0
    % two real roots
    num_roots = 2;
elseif D == 0
    % one real root
    num_roots = 1;
else
    % no real roots
    num_roots = 0;
end

end
336 chars
20 lines

To use this function, pass the coefficients a, b, and c as arguments:

main.m
a = 1;
b = 2;
c = -3;

num_roots = num_real_roots(a, b, c)  % returns 2
72 chars
6 lines

This example assumes the quadratic is of the form ax^2 + bx + c = 0 with real coefficients.

gistlibby LogSnag