Skip to main content
v2026.11,858 entries · CC-BY 4.0
LAC HealthMedical & Research SuppliesReagents, PPE & instruments — chain-of-custody documented.Fast, traceable sourcing built for regulated research environments, from bench consumables to instrumentation.Shop lac.us CodeCASRAIlac.us

Integrating MATLAB: Numerical & Symbolic Guide

A researcher guide to numerical and symbolic integration in MATLAB, covering integral, trapz, vectorization rules, error tolerances, and open alternatives.

Written and maintained by CASRAI Editorial Board

Last updated

Integrating in MATLAB refers to evaluating definite, indefinite, and numerical integrals across continuous mathematical functions, dynamic differential equations, and discrete experimental datasets. Researchers across engineering, biophysics, economics, and computational biology rely on MATLAB’s global adaptive quadrature (integral), composite trapezoidal integration (trapz), and symbolic calculus (int) to compute areas under curves, calculate cumulative energy dissipation, evaluate kinematic flux, and solve differential equations.

What it is used for in research

Mathematical integration is a foundational operation across quantitative scientific research. In experimental workflows, researchers rarely work solely with idealized algebraic functions; instead, they navigate both continuous governing differential equations and discrete time-series measurements captured by laboratory sensors. MATLAB provides tailored numerical and symbolic routines designed specifically for these distinct research contexts:

  • Experimental Signal and Sensor Analysis: Calculating cumulative physiological exposure, pharmacokinetic area under the curve (AUC), total mechanical work from force-displacement curves, or cumulative energy from electrical sensors. Discrete data vectors imported from laboratory instruments—frequently structured in a MATLAB data table—are evaluated directly using numerical array integrators like trapz and cumtrapz without fitting an artificial mathematical equation.
  • Physical and Chemical Process Modeling: Evaluating definite integrals of non-linear transport equations, chemical kinetics, and flux distributions. Specialized domain toolboxes and reaction kinetics platforms—such as the Cantera software framework—interface directly with MATLAB to evaluate multi-component reaction integrals and thermodynamic equilibria.
  • Probability and Statistical Analysis: Computing cumulative distribution functions (CDFs), expected values, and normalization constants for multi-parameter probability density functions that lack closed-form analytical solutions.
  • Dynamical Systems and Biomechanics: Integrating systems of ordinary differential equations (ODEs) using adaptive Runge-Kutta solvers like ode45 or ode15s to track trajectory states, population dynamics, or metabolic reaction networks over time.
  • Theoretical and Analytical Derivations: Deriving exact closed-form algebraic antiderivatives and evaluating symbolic definite integrals via the Symbolic Math Toolbox (int) to confirm theoretical hypotheses before implementing large-scale numerical simulations.

Comparing MATLAB integration methods

Selecting the correct integration routine depends on whether your research input is an analytical formula, a continuous function handle, or a discrete array of empirical measurements. The table below outlines the primary routines available in MATLAB:

Function Type Input Format Primary Research Use Case Key Capability
integral Numerical (Adaptive Quadrature) Function handle @(x) Continuous mathematical functions and nonlinear modeling Global adaptive mesh refinement with user-defined AbsTol and RelTol; supports infinite bounds (-Inf, Inf).
trapz Numerical (Trapezoidal Rule) Coordinate vectors X, Y Discrete laboratory data, sensor streams, and instrument logs Evaluates integrals directly on sampled data arrays without requiring an analytical equation; supports non-uniform spacing.
cumtrapz Numerical (Cumulative Trapezoidal) Coordinate vectors X, Y Time-series accumulation and cumulative energy tracking Returns a vector of identical length to the input representing running cumulative integral values across time.
integral2 / integral3 Numerical (Multidimensional) Multivariate function handle @(x,y) Spatial modeling, surface area, and volume integration Evaluates double and triple integrals over planar and non-rectangular boundary functions.
quadgk Numerical (Gauss-Kronrod) Function handle @(x) Oscillatory integrands and endpoint singularities Adaptive Gauss-Kronrod quadrature capable of integrating over infinite intervals and through branch cuts in the complex plane.
int Symbolic (Computer Algebra) Symbolic expression (syms) Theoretical derivations, proofs, and closed-form solutions Requires Symbolic Math Toolbox; outputs exact analytical expressions and exact fractions rather than floating-point approximations.

Install or access

To execute integration workflows in MATLAB, researchers can access the software through several official MathWorks deployment channels:

  • Campus-Wide Institutional License: Most major research universities and national laboratories provide institutional access via a MATLAB Campus-Wide License. Researchers link their institutional email to a MathWorks Account to activate their desktop or cloud workstation seat.
  • MATLAB Desktop: Download the official interactive installer directly from the MathWorks Downloads portal (mathworks.com/downloads). The installer supports Windows (executable installer), macOS (disk image), and Linux (interactive shell script ./install). During setup, authenticate with your MathWorks Account and ensure the core MATLAB engine and optional toolboxes (such as the Symbolic Math Toolbox for int) are selected.
  • MATLAB Online: Researchers needing immediate cloud access without installing desktop software can navigate directly to matlab.mathworks.com in any modern web browser. MATLAB Online provides a browser-based integrated development environment (IDE) that synchronizes project files automatically through MATLAB Drive.
  • High-Performance Computing and Containers: For cluster batch processing and reproducible pipelines, research computing facilities run headless MATLAB engines managed through the MathWorks Network License Manager. When building containerized reproducible research workflows, investigators frequently evaluate Docker vs virtual machines to package reproducible runtime environments containing specific MATLAB toolbox versions.

Step-by-step task

The following verified workflows demonstrate how to perform continuous numerical integration, discrete experimental data integration, and analytical symbolic integration in MATLAB.

Workflow 1: Numerical integration of a continuous function using integral

The integral function is the standard modern tool for definite integrals of continuous functions. It uses global adaptive quadrature to recursively subdivide the integration interval until the estimated numerical error falls below prescribed thresholds.

  1. Define the Integrand as a Vectorized Function Handle: The function handle must accept an array of values and return an array of corresponding function evaluations. Crucially, you must use element-wise arithmetic operators (.*, ./, .^) rather than standard matrix operators. For example, to integrate the Gaussian bell curve f(x) = exp(-x2):
    fun = @(x) exp(-x.^2);
  2. Set the Integration Limits: Define the lower limit xmin and upper limit xmax. Limits can be finite real numbers or infinite:
    xmin = 0;
    xmax = Inf;
  3. Execute the Integral with Error Tolerances: Call integral, optionally passing name-value arguments to specify absolute tolerance (AbsTol) and relative tolerance (RelTol):
    q = integral(fun, xmin, xmax, 'AbsTol', 1e-12, 'RelTol', 1e-9);
  4. Review the Numerical Result: MATLAB evaluates the integral and returns the scalar double-precision result:
    disp(q);
    % Output: 0.8862 (which equals sqrt(pi)/2)

Workflow 2: Trapezoidal numerical integration of discrete laboratory data using trapz

When working with empirical measurements—such as blood flow velocity, sensor voltage, or tensile load recorded at discrete time steps—no closed-form continuous equation exists. Use trapz to approximate the area under the curve using the composite trapezoidal rule.

  1. Prepare Coordinate Vectors: Ensure your independent variable vector X (e.g., time points) and dependent variable vector Y (e.g., sensor signal) have identical lengths:
    t = linspace(0, 10, 501);  % 501 sample points between 0 and 10 seconds
    signal = 2.5 * sin(0.5 * t) + 3.0;  % Sampled instrument response
  2. Compute Total Definite Area: Pass the coordinates to trapz(X, Y). Always pass X to account for actual physical sampling intervals rather than assuming unit spacing:
    total_integral = trapz(t, signal);
    disp(total_integral);
  3. Compute Cumulative Trajectory Over Time: If you need to monitor the progression of the integrated quantity over the course of the experiment, use cumtrapz:
    cumulative_integral = cumtrapz(t, signal);
    plot(t, cumulative_integral);
    xlabel('Time (s)');
    ylabel('Cumulative Area');
    title('Running Integral of Sensor Response');

Workflow 3: Exact analytical integration using the Symbolic Math Toolbox

If you require exact mathematical expressions rather than floating-point approximations, use the int command within the Symbolic Math Toolbox.

  1. Instantiate Symbolic Variables: Use syms to declare your variable:
    syms x;
    f = x^2 * exp(-x);
  2. Evaluate Indefinite or Definite Integrals: Call int(f, x) for an antiderivative, or pass limits for a definite evaluation:
    % Indefinite integral
    F_indef = int(f, x);
    % Output: -exp(-x)*(x^2 + 2*x + 2)
    
    % Definite integral from 0 to 1
    F_def = int(f, x, 0, 1);
    % Output: 2 - 5*exp(-1)
  3. Convert to High-Precision Numeric Values: To view the numeric equivalent of the exact symbolic expression, use vpa (variable-precision arithmetic) or double:
    numeric_val = double(F_def);
    disp(numeric_val);
    % Output: 0.1606

Output and how to read it

Understanding MATLAB’s output format ensures proper interpretation of integration results within research publications and analysis scripts:

  • Scalar Double Precision: For integral and trapz(X, Y), MATLAB outputs a scalar double-precision floating-point number (IEEE 754 standard, 64-bit). The result reflects the estimated area under the curve between the specified bounds.
  • Convergence and Tolerances: The numerical quadrature routine in integral stops subdividing intervals when the global estimated absolute error |E| satisfies:

    |E| ≤ max(AbsTol, RelTol · |q|)

    The default AbsTol is 1e-10 and RelTol is 1e-6. If your physical simulation requires higher precision (e.g., astrodynamics or molecular dynamics), you can tighten these tolerances down to machine precision limits (approximately 1e-15).
  • Vector and Matrix Dimensions: If trapz is supplied with a two-dimensional matrix Y and a coordinate vector X, MATLAB integrates along the first non-singleton dimension by default, returning a row vector containing the trapezoidal integral of each individual column.
  • Symbolic Output: The int function produces a sym class object. Symbolic expressions retain exact mathematical constants (such as pi, log(2), and fractions like 1/3) rather than truncating them into rounded decimals.

Troubleshooting

When integrating functions and data in MATLAB, researchers frequently encounter specific runtime errors and convergence warnings. The table below outlines the most frequent issues and their verified resolutions:

Error or Warning Message Root Cause Verified Solution
Error: Inner matrix dimensions must agree or Operands to the || and && operators must be convertible to logical scalar values The integrand function handle was written with matrix operators (*, /, ^) instead of element-wise array operators. integral passes a vector of sample nodes to the function. Vectorize the function handle using dot operators: replace * with .*, / with ./, and ^ with .^. Alternatively, set the name-value argument 'ArrayValued', true if the function returns an array for a scalar input.
Warning: Reached the maximum number of intervals The integrand oscillates extremely rapidly, contains steep gradients, or decays too slowly toward infinity. Partition the integration domain into smaller piecewise subintervals using the 'Waypoints' parameter, or substitute quadgk for oscillatory or infinite domains.
Warning: Minimum step size reached near x = ... The integrand exhibits a sharp internal discontinuity, vertical asymptote, or derivative singularity within the integration bounds. Specify known singularity locations inside the 'Waypoints' vector (e.g., integral(fun, 0, 5, 'Waypoints', 2)) so the quadrature routine integrates up to the singularity from both sides.
Output is NaN or Inf The function handle evaluates to 0/0 or Inf at specific boundary nodes or internal quadrature evaluation points. Evaluate the limit analytically at singular points or reformulate the function handle using conditional checks (e.g., using sinc instead of sin(x)./x).
trapz returns unexpected scalar or size mismatch The coordinate vector X and data array Y have unequal lengths or mismatched orientation (row vector vs column vector). Check dimensions using size(X) and size(Y). Ensure length(X) == size(Y, 1) or specify the dimension argument explicitly: trapz(X, Y, dim). When storing tabular data in lab databases, maintaining clean schemas in a scientific data management system (SDMS) prevents column dimensional shifts.

Free alternatives

While MATLAB is widely used across academic and corporate research centers, its commercial licensing fees can present barriers for open-science reproducibility and community data sharing. In computational research, comparative ecosystem studies—such as comparing R vs SAS or Python vs MATLAB—help labs establish accessible analysis pipelines. The following verified open-source tools provide equivalent numerical and symbolic integration capabilities:

Software / Library License Integration Functions MATLAB Syntax Compatibility Best Research Application
GNU Octave GNU GPLv3 quad, quadgk, quadcc, trapz, cumtrapz High (Near 1:1 drop-in syntax compatibility) Direct execution of existing MATLAB .m scripts without code modifications; drop-in replacement for laboratory automation.
Python (SciPy / NumPy) BSD-3-Clause scipy.integrate.quad, scipy.integrate.trapezoid, scipy.integrate.cumulative_trapezoid Moderate (Requires Python syntax and NumPy arrays) High-throughput data science, machine learning workflows, and cloud-native analysis pipelines.
Julia (QuadGK.jl) MIT License quadgk, trapz (via Trapz.jl) Moderate (Similar mathematical syntax) Large-scale computational physics, differential equation solving, and high-performance numerical simulations.
SymPy (Python) / Maxima BSD / GNU GPL sympy.integrate(), integrate() Moderate Open-source computer algebra for closed-form symbolic antiderivatives and mathematical proofs without commercial toolbox requirements.

When developing open-source scientific tools or custom integration algorithms, publishing software descriptions in peer-reviewed venues such as the Journal of Open Source Software (JOSS) ensures academic credit and verifiable code accessibility.

FAQ

What is the difference between numerical and symbolic integration in MATLAB?

Numerical integration (performed via integral, quadgk, or trapz) calculates an approximate floating-point numeric value for a definite integral by evaluating the function at specific abscissa points. Symbolic integration (performed via int in the Symbolic Math Toolbox) applies computer algebra algorithms to find the exact analytical antiderivative formula expressed in terms of mathematical variables.

How do I integrate experimental data vectors in MATLAB?

To integrate discrete data points where no continuous mathematical equation is known, use the trapz function. Provide both the coordinate vector X and measurement vector Y: q = trapz(X, Y). This applies the composite trapezoidal rule across the sampled intervals. For running cumulative integrals over time, use cumtrapz(X, Y).

Why does the integral function require element-wise operators?

The integral engine evaluates the integrand function handle across an array of quadrature test points simultaneously to optimize performance. If the function contains standard matrix operators (such as * or ^), MATLAB attempts to perform linear algebraic matrix multiplication rather than evaluating each point independently, causing a dimension mismatch error. Always define the integrand using dot operators: .*, ./, and .^.

Can MATLAB calculate double and triple integrals?

Yes. For two-dimensional definite integrals over planar regions, use integral2(fun, xmin, xmax, ymin, ymax). For three-dimensional volume integrals, use integral3(fun, xmin, xmax, ymin, ymax, zmin, zmax). Both functions support variable integration limits where boundary functions are passed as function handles.

When should I use quadgk instead of integral?

Use quadgk when your integrand contains oscillatory functions, endpoint singularities, infinite intervals with slow convergence, or when integrating along contour paths in the complex plane. quadgk uses high-order Gauss-Kronrod quadrature pairs and handles difficult boundary behaviors more robustly than standard global adaptive quadrature.

Sources

  • MathWorks Documentation. “integral: Numerical integration of function using global adaptive quadrature.” MathWorks Help Center. URL: https://www.mathworks.com/help/matlab/ref/integral.html (Accessed 2026-11-07).
  • MathWorks Documentation. “trapz: Trapezoidal numerical integration.” MathWorks Help Center. URL: https://www.mathworks.com/help/matlab/ref/trapz.html (Accessed 2026-11-07).
  • MathWorks Documentation. “int: Definite and indefinite integrals (Symbolic Math Toolbox).” MathWorks Help Center. URL: https://www.mathworks.com/help/symbolic/sym.int.html (Accessed 2026-11-07).
  • MathWorks Documentation. “Install Products with Internet Connection.” MathWorks Help Center. URL: https://www.mathworks.com/help/install/ug/install-products-with-internet-connection.html (Accessed 2026-11-07).
  • GNU Octave Documentation. “Numerical Integration: quad and trapz.” Octave Documentation Release 9. URL: https://docs.octave.org/latest/Numerical-Integration.html (Accessed 2026-11-07).
  • SciPy Community. “Integration and ODEs (scipy.integrate).” SciPy v1.14 Reference Guide. URL: https://docs.scipy.org/doc/scipy/reference/integrate.html (Accessed 2026-11-07).

Follow CASRAI

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

Ask CASRAI · free to try

Ask about Integrating MATLAB: Numerical & Symbolic Guide

Ask your first 2 questions free below. Subscribers get 150 a day for $29 a month.

An AI assistant specialized in research administration. It cites the sources behind every answer, labels web answers and says when it can't answer.

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 free 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 →