To create a function that solves a quadratic equation in MATLAB, you can follow these steps:
main.m337 chars14 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.m96 chars10 lines
Output:
main.m11 chars4 lines
In this example, the quadratic equation is x^2 - 5x + 6 = 0
, and the roots are 3 and 2.
gistlibby LogSnag