How to Solve Quadratic Equations in MATLAB

Sheeraz Gul Feb 02, 2024
  1. Use the solve() Method to Solve Quadratic Equations in MATLAB
  2. Create User-Defined Function to Solve Quadratic Equations in MATLAB
How to Solve Quadratic Equations in MATLAB

This tutorial will demonstrate how to solve quadratic equations in MATLAB.

Use the solve() Method to Solve Quadratic Equations in MATLAB

The solve() function can solve the quadratic equation and get the roots for us. It can also solve the higher-order equation. Let’s try to solve quadratic equations using the solve() method:

syms x
quad_equation1 = x^2 + 7*x + 10 == 0;
quad_equation2 = 7*x^2 + 5*x + 10 == 0;

X = solve(quad_equation1, x);
Y = solve(quad_equation2, x);

disp('The first root of the first quadratic equation is: '), disp(X(1));
disp('The second root of the first quadratic equation is: '), disp(X(2));

disp('The first root of the second quadratic equation is: '), disp(Y(1));
disp('The second root of the second quadratic equation is: '), disp(Y(2));

The code above tries to solve two given quadratic equations using the solve() method.

Output:

The first root of the first quadratic equation is:
-5

The second root of the first quadratic equation is:
-2

The first root of the second quadratic equation is:
- (255^(1/2)*1i)/14 - 5/14

The second root of the second quadratic equation is:
(255^(1/2)*1i)/14 - 5/14

Create User-Defined Function to Solve Quadratic Equations in MATLAB

We can create our function to solve the quadratic equations in MATLAB. We require the quadratic formula and the coefficients of a quadratic equation.

The function to solve the quadratic equations will be:

function [x1, x2] = QuadraticEquation(a, b, c)

    % quad. formula
    d = b^2 - 4*a*c;
    % the real numbered distinct roots
    if d > 0
        x1 = (-b+sqrt(d))/(2*a);
        x2 = (-b-sqrt(d))/(2*a);
    % the real numbered degenerate root
    elseif d == 0
        x1 = -b/(2*a);
        x2 = NaN;
    % complex roots will return NaN, NaN.
    else
        x1 = NaN;
        x2 = NaN;
    end
end

In the code above, a, b, and c are the coefficients of quadratic equations, and d is the quadratic formula.

Now, let’s try to solve quadratic equations using the function above. We need the coefficients of quadratic equations as inputs.

Example:

[x1, x2] = QuadraticEquation (3, 4, -13)

[y1, y2] = QuadraticEquation (1,2,1)

[z1, z2] = QuadraticEquation (3, 3, 1)

Output:

x1 =

    1.5191


x2 =

   -2.8525


y1 =

    -1


y2 =

   NaN


z1 =

   NaN


z2 =

   NaN
Author: Sheeraz Gul
Sheeraz Gul avatar Sheeraz Gul avatar

Sheeraz is a Doctorate fellow in Computer Science at Northwestern Polytechnical University, Xian, China. He has 7 years of Software Development experience in AI, Web, Database, and Desktop technologies. He writes tutorials in Java, PHP, Python, GoLang, R, etc., to help beginners learn the field of Computer Science.

LinkedIn Facebook

Related Article - MATLAB Equation