create a function to solve quadratic equation in matlab

To create a function to solve a quadratic equation in MATLAB, you can use the following code:

main.m
function [x1, x2] = solveQuadratic(a, b, c)
    % Calculate the discriminant
    discriminant = b^2 - 4*a*c;
    
    % Check if the discriminant is negative, indicating no real roots
    if discriminant < 0
        disp('No real roots');
        x1 = NaN;
        x2 = NaN;
        return;
    end
    
    % Calculate the two roots
    x1 = (-b + sqrt(discriminant)) / (2*a);
    x2 = (-b - sqrt(discriminant)) / (2*a);
end
426 chars
17 lines

This function takes three input parameters a, b, and c, which are the coefficients of the quadratic equation ax^2 + bx + c = 0. It returns two output parameters x1 and x2, which are the roots of the quadratic equation.

You can call this function by passing the coefficients of the quadratic equation as arguments. For example:

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

[x1, x2] = solveQuadratic(a, b, c);

disp(['x1 = ', num2str(x1)]);
disp(['x2 = ', num2str(x2)]);
120 chars
9 lines

Output:

main.m
x1 = 2
x2 = 1
14 chars
3 lines

This will calculate and display the roots of the quadratic equation. Note that if the discriminant is negative (indicating no real roots), the function will display a message and return NaN for both x1 and x2.

related categories

gistlibby LogSnag