create a function that solves the quadratic equation in matlab

To create a function that solves a quadratic equation in MATLAB, you can follow these steps:

main.m
function [x1, x2] = solveQuadratic(a, b, c)
    % Calculate discriminant
    discriminant = b^2 - 4*a*c;

    % Check if the equation has real roots
    if discriminant < 0
        error('Equation has no real roots');
    end

    % Calculate roots
    x1 = (-b + sqrt(discriminant))/(2*a);
    x2 = (-b - sqrt(discriminant))/(2*a);
end
337 chars
14 lines

In this code snippet, we defined a function called solveQuadratic that takes three input parameters a, b, and c. It calculates the discriminant of the quadratic equation using the formula b^2 - 4*a*c.

Next, it checks if the discriminant is less than 0, which means the equation has no real roots. In this case, the function throws an error.

If the discriminant is greater than or equal to 0, the function calculates the roots using the quadratic formula: x1 = (-b + sqrt(discriminant))/(2*a) and x2 = (-b - sqrt(discriminant))/(2*a). It then returns the roots x1 and x2.

You can call this function by passing the coefficients a, b, and c of the quadratic equation as arguments, and it will return the roots.

Here's an example usage:

main.m
a = 1;
b = -5;
c = 6;

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

disp('Roots:');
disp(x1);
disp(x2);
96 chars
10 lines

Output:

main.m
Roots:
3
2
11 chars
4 lines

In this example, the quadratic equation is x^2 - 5x + 6 = 0, and the roots are 3 and 2.

related categories

gistlibby LogSnag