Skip to main content
v2026.11,986 entries · CC-BY 4.0

fsolve MATLAB: Solve Nonlinear Equation Systems

Learn how to use fsolve in MATLAB to solve systems of nonlinear equations, configure optimoptions, provide Jacobians, and diagnose convergence exit flags.

Written and maintained by CASRAI Editorial Board

Published · Last updated

On this page

Researchers modeling physical equilibria, reaction kinetics, structural deformations, or multi-market economic balances frequently encounter coupled systems of nonlinear equations that lack closed-form analytical solutions. In numerical computing, MATLAB provides the fsolve function within its Optimization Toolbox to compute high-precision numerical roots for multivariate nonlinear systems of the form F(x) = 0. This guide explains how to formulate equation residuals, configure optimization algorithms, supply analytical Jacobians, and interpret diagnostic termination flags.

What it is used for in research

The primary purpose of fsolve in research computing is finding numerical vectors x that simultaneously satisfy a set of coupled nonlinear equations. Unlike single-equation root finding or linear matrix algebra, nonlinear systems involve transcendental functions, cross-product couplings, or polynomial powers where standard linear algebra solvers cannot be applied.

fsolve vs Other MATLAB Solvers

Understanding when to employ matlab fsolve instead of alternative MATLAB solvers prevents significant computational inefficiencies:

  • fsolve vs solve (Symbolic Math Toolbox): The symbolic solve function seeks exact algebraic expressions using computer algebra algorithms. While useful for small, low-degree polynomial systems, symbolic elimination rapidly becomes computationally intractable or fails entirely on equations with non-integer exponents or transcendental terms. For numerical simulation pipelines, a dedicated numerical MATLAB equation solver approach via fsolve offers predictable execution times and scales to hundreds of equations.
  • fsolve vs fzero (Base MATLAB): Base MATLAB includes fzero, which finds a zero of a continuous single-variable scalar function f(x) = 0 using bracketing and secant methods. Crucially, fzero cannot solve systems of multiple equations with multiple unknowns; multidimensional systems require fsolve.
  • fsolve vs lsqnonlin (Optimization Toolbox): Both solvers handle nonlinear vector residuals, but fsolve seeks exact roots where F(x) = 0 in square systems (or determined systems). When an exact root does not exist, or when researchers must enforce strict lower and upper parameter bounds (lb ≤ x ≤ ub), lsqnonlin should be used instead.

Research Application Domains

Coupled nonlinear equations solved with fsolve in matlab appear across diverse scientific disciplines:

  • Chemical and Process Engineering: Calculating steady-state vapor-liquid equilibrium (VLE) flash conditions using non-ideal activity coefficient models (NRTL, UNIQUAC) and solving simultaneous multi-reaction equilibrium kinetics.
  • Structural and Mechanical Engineering: Solving geometric constraint systems in multibody kinematics, nonlinear truss equilibrium equations under large displacements, and thermal stress balances.
  • Quantitative Economics and Econometrics: Computing stationary state vectors in dynamic stochastic general equilibrium (DSGE) models and solving coupled market-clearing price systems across interrelated commodity markets.
  • Computational Biology: Determining steady-state concentrations in complex metabolic networks and biochemical signaling pathways modeled by nonlinear Hill equations.

How to install or access it

The fsolve function is part of the MathWorks Optimization Toolbox. It is not bundled with base MATLAB and must be licensed and installed separately.

Checking Toolbox License and Installation

Before writing analysis scripts, verify that the Optimization Toolbox is installed and an available license seat exists on your system:

% Test if an Optimization Toolbox license is available
hasLicense = license('test', 'Optimization_Toolbox');
if ~hasLicense
    error('Optimization Toolbox license is not available.');
end

% Display installed version and release information
ver('optim')

Installing via MATLAB Desktop

If the toolbox is not present in your local environment, install it through the official MathWorks Add-On Explorer:

  1. Launch MATLAB Desktop.
  2. In the top toolstrip, select the Home tab.
  3. Navigate to the Environment section, click the Add-Ons dropdown menu, and select Get Add-Ons.
  4. In the Add-On Explorer search bar, enter Optimization Toolbox.
  5. Select the official MathWorks product card and click Install. Complete the installation wizard (administrative privileges or an active MathWorks account linked to your institutional license entitlement may be required).

When structuring multi-file research projects and custom utility modules, review best practices in MATLAB coding to ensure consistent path management and function encapsulation.

Accessing via MATLAB Online

Researchers accessing MATLAB via MATLAB Online in a web browser have the Optimization Toolbox pre-configured if it is included under their university campus-wide or corporate site license. No manual file downloads or local compiler configurations are required.

Step-by-step instructions

This workflow demonstrates solving a coupled, parameterized two-equation nonlinear chemical equilibrium system using fsolve in MATLAB.

Task: Solving a Coupled Nonlinear System

  1. Formulate the equations in standard residual form:
    Rearrange your physical equations so that all terms appear on the left-hand side, equating the vector to zero: F(x) = 0.
    Consider the coupled system:
    F₁(x₁, x₂) = x₁² + x₂² – 10 = 0
    F₂(x₁, x₂) = x₁ · x₂ + 2x₁ – 4 = 0
  2. Define the vector residual function:
    Create a function file or an anonymous function handle that accepts the unknown vector x and returns column vector F. When experimental parameters must be passed into the model, wrap the parameterized function within an anonymous handle:

    % Define model parameters
    target_radius_sq = 10;
    coupling_offset = 4;
    
    % Define anonymous residual function capturing parameters
    residual_system = @(x) [
        x(1)^2 + x(2)^2 - target_radius_sq;
        x(1)*x(2) + 2*x(1) - coupling_offset
    ];
  3. Specify an initial guess vector (x0):
    Because fsolve uses local iterative search algorithms, convergence speed and the specific solution branch found depend heavily on the starting estimate. Select physically realistic starting values:

    x0 = [1.0; 1.0]; % Initial guess for [x1; x2]
  4. Configure solver options with optimoptions:
    Use the optimoptions command to select the algorithm, adjust convergence tolerances, and enable iteration telemetry:

    options = optimoptions('fsolve', ...
        'Algorithm', 'trust-region-dogleg', ...
        'Display', 'iter', ...
        'FunctionTolerance', 1e-6, ...
        'StepTolerance', 1e-6, ...
        'MaxIterations', 400);
  5. Execute fsolve and capture all outputs:
    Run the solver and extract the solution vector, function residual values, exit flag, and iteration metadata:

    [x_sol, fval, exitflag, output, jacobian] = fsolve(residual_system, x0, options);

Advanced Task: Supplying Analytical Jacobians

By default, fsolve approximates partial derivatives using finite differences. For high-dimensional systems or stiff equations, finite differences can introduce numerical truncation errors and require N additional function evaluations per iteration step. Supplying an exact analytical Jacobian evaluated alongside residuals accelerates convergence and prevents numerical instability. Analytical derivatives can be derived mathematically or verified using diff in MATLAB.

Define a function file coupled_system_with_jac.m:

function [F, J] = coupled_system_with_jac(x)
    % Compute residual vector F
    F = [x(1)^2 + x(2)^2 - 10;
         x(1)*x(2) + 2*x(1) - 4];

    % Compute analytical Jacobian matrix J (dF_i / dx_j)
    if nargout > 1
        J = [2*x(1),       2*x(2);
             x(2) + 2,     x(1)];
    end
end

Instruct fsolve to use the user-supplied Jacobian by setting SpecifyObjectiveGradient to true:

options_jac = optimoptions('fsolve', ...
    'Algorithm', 'trust-region', ...
    'SpecifyObjectiveGradient', true, ...
    'Display', 'final');

[x_sol, fval, exitflag, output] = fsolve(@coupled_system_with_jac, [1.0; 1.0], options_jac);

Output and how to read it

Capturing the full return argument signature [x, fval, exitflag, output, jacobian] allows researchers to verify the numerical validity of the solution.

Diagnostic Return Arguments

  • x: The computed solution vector of decision variables.
  • fval: The residual vector evaluated at x. For an exact root, each component should be near zero (typically ≤ FunctionTolerance). If fval is far from zero, a true root was not reached.
  • exitflag: An integer code detailing why the solver terminated. Positive values indicate convergence, while zero or negative values indicate failure or early termination.
  • output: A structure containing solver execution telemetry:
    • output.iterations: Number of iterations performed.
    • output.funcCount: Total objective function evaluations.
    • output.algorithm: The algorithm executed (e.g., 'trust-region-dogleg').
    • output.firstorderopt: First-order optimality measure (norm of the gradient of the squared residual).
    • output.message: Detailed exit message describing the stopping condition.
  • jacobian: The evaluated Jacobian matrix J(x) at the final solution point.

Exit Flag Interpretation Matrix

The following table lists the official MathWorks exit flag codes returned by fsolve:

Exit Flag Status Category Official MathWorks Definition & Meaning
1 Success Function converged to a solution x. First-order optimality measure is smaller than FunctionTolerance.
2 Success Change in x was smaller than StepTolerance, or Jacobian condition met.
3 Success Change in the residual sum of squares was smaller than FunctionTolerance.
4 Success Magnitude of search direction was smaller than specified tolerance.
0 Limit Reached Number of iterations exceeded MaxIterations or evaluations exceeded MaxFunctionEvaluations.
-1 User Halted Algorithm terminated by an output function or plot function.
-2 Failure Algorithm converged to a point that is a local minimum of the sum of squares, but residual norm is large (no root found).
-3 Failure Radius of the trust region became too small without meeting tolerance conditions.

Troubleshooting

When solving complex nonlinear systems, algorithms may fail to converge due to poor initial guesses, ill-conditioned matrices, or non-smooth equations. Below are standard diagnostic remedies for common errors:

1. Solver Exits with Flag -2 (Local Minimum Trap)

Symptom: The solver stops and reports that it converged to a local minimum of the squared residuals, but the residual vector fval is significantly non-zero.
Cause: fsolve minimizes the scalar objective S(x) = ∑ F_i(x)². If the landscape contains a local depression where ∇S(x) ≈ 0 but S(x) > 0, the algorithm stalls without finding a root.
Remedy:

  • Supply a different starting vector x0 closer to the expected physical regime.
  • Use a multi-start grid approach to test multiple initial candidate points.
  • Switch algorithm to Levenberg-Marquardt: optimoptions('fsolve', 'Algorithm', 'levenberg-marquardt'), which handles non-square or ill-conditioned topologies more flexibly than trust-region-dogleg.

2. Exceeded MaxIterations or MaxFunctionEvaluations (Exit Flag 0)

Symptom: The solver terminates after hundreds of iterations without satisfying convergence criteria.
Cause: The system is highly nonlinear, poorly scaled, or the specified tolerance is tighter than machine precision allows.
Remedy:

  • Increase iteration bounds: optimoptions('fsolve', 'MaxIterations', 2000, 'MaxFunctionEvaluations', 10000).
  • Check variable scaling. If one unknown variable represents pressure in Pascals (10⁵) and another represents molar fraction (10⁻³), normalize all variables to order-of-magnitude unity.
  • Inspect intermediate progress by setting 'Display', 'iter' to observe whether the residual norm is decreasing or oscillating.

3. Ill-Conditioned or Singular Jacobian Warning

Symptom: MATLAB emits a warning: Matrix is close to singular or badly scaled. Results may be inaccurate.
Cause: Equations in the system are linearly dependent at the current iterate, or variables have zero derivative with respect to certain equations.
Remedy:

  • Check your mathematical equations for algebraic redundancy (e.g., linear combinations of other equations).
  • Supply an analytical Jacobian matrix via SpecifyObjectiveGradient to eliminate finite-difference approximation errors near singular points.
  • Switch to the Levenberg-Marquardt algorithm, which adds an adaptive damping regularizer λI to stabilize matrix inversion during iterations.

4. Complex or NaN Values Encountered

Symptom: The solver throws an error stating that user functions returned complex or NaN values.
Cause: The search step pushed an iterate into a domain where square roots, fractional exponents, or logarithms are undefined for negative numbers.
Remedy:

  • Apply domain parameter transformations. For example, replace a strictly positive parameter x with exp(u) so that u can vary freely over the real line.
  • If explicit box constraints are required, reformulate the problem using lsqnonlin with lower and upper bounds lb and ub, as fsolve does not accept bound constraints.

Free alternatives

Researchers working in open-source workflows or without active MATLAB Optimization Toolbox licenses can implement numerical nonlinear solvers across several established open-source environments. For broader software selection criteria, consult our comparative analysis of MATLAB vs R.

Environment / Library License Primary Solver Routine Underlying Numerical Engine Key Syntax & Operational Difference
GNU Octave GPLv3 (Free Software) fsolve(fcn, x0, options) MINPACK hybrd subroutine (modified Powell hybrid method) Near 100% syntax compatibility with MATLAB; built-in without requiring an add-on toolbox. Uses optimset for options.
SciPy (Python) BSD 3-Clause scipy.optimize.root(fun, x0, method='hybr') MINPACK hybrd (Powell hybrid) and lm (Levenberg-Marquardt) Returns an OptimizeResult object with .x, .fun, and .success. Supports non-MINPACK large-scale solvers (Krylov, Broyden).
Julia (NLsolve.jl) MIT License nlsolve(f, x0) Trust-region, Newton-Raphson, and Anderson acceleration High performance compiled execution; integrates natively with Julia’s ForwardDiff.jl for automatic differentiation without manual Jacobians.
R (nleqslv) GPL-2 | GPL-3 nleqslv(x, fn, method="Broyden") Newton and Broyden secant algorithms with line search or trust region Standard package in the CRAN repository; designed for econometric and biometric nonlinear equation modeling.

FAQ

What is the difference between fsolve and fzero in MATLAB?

The fzero function in base MATLAB solves a single nonlinear algebraic equation with one variable (f(x) = 0) using root bracketing and interpolation. In contrast, fsolve is an Optimization Toolbox function designed to solve coupled systems of multiple nonlinear equations with multiple unknowns (F(x) = 0). You cannot use fzero for multidimensional systems.

How do you pass extra parameters or constants to fsolve?

To pass fixed model coefficients or constants into your residual function without using global variables, wrap your parameterized function inside an anonymous function handle. For example, if your residual function is defined as function F = my_model(x, a, b), pass @(x) my_model(x, a, b) as the first argument to fsolve.

Does fsolve support lower and upper bound constraints?

No, fsolve does not support bound constraints (lb ≤ x ≤ ub). If your research problem requires variables to remain within specified bounds (such as non-negative concentrations or probabilities between 0 and 1), formulate the problem as a nonlinear least-squares problem using lsqnonlin with identical residuals, or transform the variables mathematically (e.g., using exponential transformations).

Can fsolve be run without an Optimization Toolbox license?

No. fsolve is part of the MathWorks Optimization Toolbox and requires a valid toolbox license seat. If you do not have access to this toolbox, you can run identical code in GNU Octave, which provides a built-in fsolve implementation based on MINPACK without requiring commercial add-on licenses.

Why does fsolve terminate with exit flag -2?

Exit flag -2 indicates that fsolve converged to a point that is a local minimum of the sum of squared residuals, but the residual vector is significantly non-zero. The algorithm stalled in a local basin without finding an actual root where F(x) = 0. To resolve this, supply a different initial guess x0 closer to the physical solution or switch to the 'levenberg-marquardt' algorithm.

Sources

Follow CASRAI

Research-administration guidance, standards updates and independent tool reviews.

Ask CASRAI · full access

Ask about fsolve MATLAB: Solve Nonlinear Equation Systems

Full access: large monthly usage, up to 10 source passages behind each answer, and MCP and API access for Claude Code, Codex and other CLIs. Cancel any time.

An AI assistant for research: funder rules, compliance, methods and publishing. It links the sources behind its answers and labels answers that come from a web search.

Answers draw on CASRAI's guides and dictionary plus the federal and funder documents we index: Federal Register, Grants.gov, Regulations.gov and UKRI.

Works on this site and inside Claude, Cursor and the AI tools you already use.

Everything CASRAI publishes — this page, the dictionary, the guides and the news — stays open to read, with no account and no card.

Referenced across the research world

University of Cambridge logoColumbia University logoCrossref logoUniversity of Edinburgh logoHarvard University logoUniversity of Oxford logoPrinceton University logoStanford School of Medicine logoUniversity College London logoORCID logoUniversity of Cambridge logoColumbia University logoCrossref logoUniversity of Edinburgh logoHarvard University logoUniversity of Oxford logoPrinceton University logoStanford School of Medicine logoUniversity College London logoORCID logo
  • University of Cambridge logo
  • Columbia University logo
  • Crossref logo
  • University of Edinburgh logo
  • Harvard University logo
  • University of Oxford logo
  • Princeton University logo
  • Stanford School of Medicine logo
  • University College London logo
  • ORCID logo

View CASRAI adoption →