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

MATLAB Interpolation: interp1, Gridded Data Guide

Estimate unmeasured data points in MATLAB using interp1, griddedInterpolant, and griddata. Compare linear, cubic spline, pchip, and makima methods.

Written and maintained by CASRAI Editorial Board

Published

On this page

In scientific computing, MATLAB interpolation estimates function values at unmeasured query coordinates using a discrete set of known sample data points. Researchers across computational physics, biomedical engineering, environmental modeling, and econometrics rely on interpolation in MATLAB to resample non-uniform experimental time series, reconstruct high-resolution surfaces from sparse spatial meshes, and evaluate thermodynamic or aerodynamic calibration tables. Unlike regression or empirical curve fitting, which minimizes residual errors without necessarily passing through observations, interpolation constructs a continuous mathematical interpolant that passes precisely through every known sample point.

The core computational engine in MATLAB provides dedicated routines tailored to distinct dimensional structures and spatial configurations: interp1 for one-dimensional signals, interp2 and interpn for multi-dimensional rectilinear grids, griddedInterpolant for high-throughput repetitive queries, and griddata or scatteredInterpolant for unstructured Delaunay triangulations. Selecting the appropriate algorithm—balancing piecewise linear continuity against C¹ shape-preserving Hermite polynomials (pchip, makima) or C² cubic splines—is essential to prevent artificial numerical oscillations, preserve physical conservation laws, and maintain scientific validity.

What it is used for in research

Interpolation with MATLAB is an essential data processing step across empirical and numerical research programs. Because experimental instruments, field sensors, and computational simulations frequently capture data at differing rates or irregular spatial coordinates, interpolation provides the mathematical foundation for data harmonization and synthesis.

Key academic and scientific applications include:

  • Sensor Synchronization and Non-Uniform Resampling: In physiological monitoring and telemetry, physical sensors (such as EEG electrodes, accelerometers, and pulse oximeters) often log measurements at asynchronous timestamps or fluctuating clock intervals. 1-D interpolation resamples these disjointed streams onto a unified, equidistant time vector, enabling synchronized multi-channel spectral analysis; for downstream frequency-domain processing, see our guide on MATLAB signal analysis workflows.
  • Surface and Volumetric Grid Reconstruction: Environmental and oceanographic field surveys frequently record salinity, temperature, or pollutant concentrations at sparse, irregular GPS coordinates. Multi-dimensional interpolation maps these scattered measurements onto dense Cartesian grids required for numerical fluid dynamics and climate circulation models.
  • Lookup Tables and State Variable Calibration: Experimental physical chemistry and materials science rely on discrete calibration tables relating temperature, pressure, enthalpy, or reaction kinetics. Interpolation allows automated computational solvers to estimate intermediate state variables on demand without requiring slow physical measurements at every point.
  • Data Imputation Across Missing Acquisition Windows: When transient hardware drops or transmission timeouts cause gaps in observational datasets, interpolation bridges missing values. While localized gaps can be reconstructed via interpolation, researchers evaluating noisy background trends often combine interpolation with moving-average smoothing to characterize baseline signals.

A critical methodological decision in quantitative research is choosing between interpolation and curve fitting. While interpolation forces the mathematical curve to pass exactly through every knot (P(x_k) = y_k), regression models minimize an objective loss function (such as least-squares residuals) to capture underlying trends amidst stochastic noise. For experimental datasets dominated by measurement error, consult our companion guide on MATLAB curve fitting and regression.

Install or access

Core interpolation routines—including interp1, interp2, interpn, griddedInterpolant, griddata, and scatteredInterpolant—are built-in components of standard MATLAB. They are included directly in the base installation and do not require additional commercial toolbox licenses.

Researchers can access MATLAB through official MathWorks distribution channels:

  • Campus-Wide and Institutional Access: Most research universities and national laboratories provide Total Academic Headcount (TAH) licenses. Academic researchers can authenticate using their institutional single sign-on (SSO) credentials at the MathWorks portal; for setup steps, see our overview of installing and configuring MATLAB.
  • Local Desktop Workstation: Standalone desktop binaries are available for 64-bit Windows, macOS (native Apple Silicon and Intel x86_64), and standard Linux distributions (Ubuntu, RHEL, SUSE). Local installations leverage multi-core multithreading and BLAS/LAPACK optimizations for matrix-based interpolation calculations.
  • MATLAB Online: Researchers working in cloud or collaborative settings can execute MATLAB scripts and evaluate interpolants directly inside any modern web browser via matlab.mathworks.com without maintaining a local operating system installation.
  • High-Performance Computing (HPC) Batch Execution: For large-scale parameter sweeps and multi-dimensional grid interpolation, MATLAB runs headless on HPC compute nodes using non-interactive execution: matlab -batch "run_pipeline".

To verify that MATLAB is properly installed and check the active environment version from the command window, execute:

ver('matlab')
license('inuse')

Step-by-step task

The following numbered procedures provide verified, production-ready MATLAB workflows for one-dimensional interpolation, high-throughput gridded interpolation, and scattered spatial data reconstruction.

Task 1: One-Dimensional Interpolation Using interp1

One-dimensional interpolation estimates unmeasured values along a single continuous coordinate axis (such as time, wavelength, or axial distance).

  1. Prepare and Validate Monotonic Sample Points:

    Sample points x must be real, finite, and strictly monotonic. If your raw experimental data contains unsorted coordinates or duplicate measurement timestamps, sort and isolate unique entries first:

    % Raw experimental calibration data
    x_raw = [0.0, 1.2, 2.5, 3.8, 5.0, 6.2, 7.5, 8.8, 10.0];
    v_raw = [0.00, 0.93, 0.60, -0.60, -0.96, -0.08, 0.94, 0.54, -0.54];
    
    % Ensure strict monotonicity and remove duplicate coordinates
    [x, unique_idx] = unique(x_raw);
    v = v_raw(unique_idx);
  2. Define Query Coordinates:

    Construct a fine query vector xq spanning the interval of interest by generating regular query coordinates with linspace:

    % Generate 200 evenly spaced query evaluation points
    xq = linspace(min(x), max(x), 200);
  3. Execute interp1 with the Desired Algorithm:

    Pass the sample coordinates, sample values, query coordinates, and the chosen interpolation method string ('linear', 'spline', 'pchip', or 'makima'):

    % Evaluate linear, cubic spline, and shape-preserving PCHIP
    vq_linear = interp1(x, v, xq, 'linear');
    vq_spline = interp1(x, v, xq, 'spline');
    vq_pchip  = interp1(x, v, xq, 'pchip');
    vq_makima = interp1(x, v, xq, 'makima');
  4. Configure Boundary Extrapolation Behavior:

    By default, query points lying outside [min(x), max(x)] evaluate to NaN. To enable mathematical extrapolation beyond sample bounds, supply 'extrap' as the trailing parameter, or provide a scalar constant (such as 0) to assign a fallback value:

    % Extrapolate using PCHIP algorithm
    vq_extrap = interp1(x, v, [-1.0, 5.0, 11.0], 'pchip', 'extrap');
    
    % Fill out-of-bounds queries with a fixed sentinel value (0.0)
    vq_bounded = interp1(x, v, [-1.0, 5.0, 11.0], 'linear', 0.0);
  5. Inspect and Visualize Results:

    Plot the original discrete sample knots against the continuous interpolated trajectories to confirm algorithm fidelity:

    figure;
    plot(x, v, 'ko', 'MarkerFaceColor', 'k', 'DisplayName', 'Sample Knots'); hold on;
    plot(xq, vq_linear, 'b--', 'LineWidth', 1.2, 'DisplayName', 'Linear');
    plot(xq, vq_spline, 'r-',  'LineWidth', 1.2, 'DisplayName', 'Cubic Spline');
    plot(xq, vq_pchip,  'g-.', 'LineWidth', 1.5, 'DisplayName', 'PCHIP (Shape-Preserving)');
    plot(xq, vq_makima, 'm:',  'LineWidth', 1.5, 'DisplayName', 'Makima');
    grid on;
    xlabel('Independent Coordinate x');
    ylabel('Observed / Interpolated Value v');
    title('1-D Interpolation Method Comparison');
    legend('Location', 'Best');

Task 2: High-Throughput Gridded Interpolation with griddedInterpolant

When working with multi-dimensional datasets sampled on structured Cartesian grids (such as image slices, spatial climate matrices, or parameter grids), griddedInterpolant provides significant speed advantages over legacy interp2 or interpn by pre-computing grid geometry once.

  1. Define the Source Grid and Sample Array:

    Define coordinate vectors for each dimension using ndgrid:

    % Define 2-D rectilinear grid coordinates
    x_grid = 1:0.5:10;
    y_grid = 1:0.5:8;
    [X, Y] = ndgrid(x_grid, y_grid);
    
    % Generate sample values across the 2-D grid
    V = sin(X) .* cos(Y ./ 2);
  2. Instantiate the griddedInterpolant Object:

    Create an interpolant object specifying the interpolation and extrapolation algorithms:

    % Instantiate object: method = 'pchip', extrapolation = 'nearest'
    F = griddedInterpolant(X, Y, V, 'pchip', 'nearest');
  3. Evaluate Query Coordinates Repeatedly:

    Query the object using dense arrays or single evaluation points without paying repeated grid-parsing overhead:

    % Dense query grid for simulation
    [Xq, Yq] = ndgrid(1:0.05:10, 1:0.05:8);
    Vq = F(Xq, Yq);
    
    % Visualize the resulting surface
    figure;
    surf(Xq, Yq, Vq, 'EdgeColor', 'none');
    xlabel('Coordinate X'); ylabel('Coordinate Y'); zlabel('Interpolated Value V');
    title('Dense 2-D Grid Interpolation using griddedInterpolant');
    view(45, 30);

    For additional figure customization techniques, see our guide to visualizing 3D surfaces and meshes.

Task 3: Unstructured Spatial Interpolation Using scatteredInterpolant

When observational measurements do not fall on an orderly grid (e.g., mobile weather stations, ocean drift buoys, or geological boreholes), use Delaunay-triangulation based interpolation.

  1. Organize Scattered Coordinate Vectors:

    Collect coordinates into column vectors:

    % 150 non-uniform, randomly distributed observation points
    rng(42); % Fixed seed for reproducibility
    x_scat = 10 * rand(150, 1);
    y_scat = 10 * rand(150, 1);
    v_scat = sin(x_scat) + cos(y_scat);
  2. Construct the scatteredInterpolant Object:

    Pass the coordinate vectors and values to scatteredInterpolant. Natural neighbor interpolation ('natural') provides smooth C¹ continuity across non-uniform points:

    F_scat = scatteredInterpolant(x_scat, y_scat, v_scat, 'natural', 'none');
  3. Evaluate Across a Uniform Query Grid:

    Generate Cartesian query points using meshgrid and evaluate:

    [Xq_mesh, Yq_mesh] = meshgrid(0:0.2:10, 0:0.2:10);
    Vq_scat = F_scat(Xq_mesh, Yq_mesh);

    Query points falling outside the convex hull of the original scattered coordinates evaluate to NaN when extrapolation is set to 'none', preventing invalid boundary distortions.

Output and how to read it

Understanding and reading the output from MATLAB interpolation routines requires verifying dimensional conformity, assessing boundary completeness, and validating mathematical behavior.

Output Dimensionality and Type

The output array returned by interp1(x, v, xq, ...) or evaluated via F(Xq, Yq) strictly mirrors the size and dimensionality of the query coordinates. If xq is a 1×N row vector, the output is a 1×N row vector. If xq is an M×N matrix, the output matches that M×N dimension. When sample values v constitute an N-by-P matrix, interp1 performs interpolation down each column independently, returning an output of size length(xq)-by-P.

Mathematical Method Characteristics

Selecting among interpolation algorithms involves explicit trade-offs between derivative continuity and shape preservation:

Method Name Continuity Class Monotonicity Preserved? Runge / Overshoot Risk Primary Research Suitability
‘linear’ C⁰ (Continuous function, discontinuous 1st derivative) Yes None (Bounded strictly by adjacent points) High-speed lookups, coarse sensor data, financial price ticks.
‘nearest’ Discontinuous (C⁻¹ step function) Yes (Stepwise) None Categorical classifications, land-use zoning grids, discrete state flags.
‘spline’ C² (Continuous 1st and 2nd derivatives) No High (Subject to overshoot oscillations near sharp steps) Smooth trajectory planning, robotic kinematics, orbital physics, potential fields.
‘pchip’ C¹ (Continuous 1st derivative) Yes (Local monotonicity strictly enforced) None (Eliminates artificial extrema) Thermodynamic state equations, chemical kinetics, positive concentrations.
‘makima’ C¹ (Modified Akima cubic Hermite) Partial (Locally constrained) Very Low (Minimizes overshoot without flattening peaks) Spectroscopic baselines, acoustic waveforms, seismic signal profiles.

Validating Knot Exactness and Monotonicity

To verify output integrity in automated scientific code, perform diagnostic assertion checks:

  • Knot Exactness: Interpolation guarantees that evaluating query points at the original sample locations returns the exact original values within machine precision ε (eps):
    v_test = interp1(x, v, x, 'spline');
    max_knot_error = max(abs(v_test - v));
    assert(max_knot_error < 1e-12, 'Interpolation failed knot exactness check');
  • Preservation of Monotonicity: For physical quantities that must not decrease (such as cumulative probabilities or total mass), test that the finite difference of the interpolated array retains consistent signs:
    is_strictly_monotonic = all(diff(vq_pchip) > 0);

Troubleshooting

Error: “The grid vectors must be strictly monotonic”

Cause: The sample vector x contains out-of-order coordinate values or duplicate points (e.g., repeated timestamps from logging collisions).

Solution: Sort the vector and remove duplicates using the unique function before passing data to interp1:

% Identify unique entries and extract corresponding values
[x_clean, unique_idx] = unique(x_raw, 'stable');
v_clean = v_raw(unique_idx);

% If raw coordinates were unsorted, sort ascending
[x_sorted, sort_idx] = sort(x_clean, 'ascend');
v_sorted = v_clean(sort_idx);

vq = interp1(x_sorted, v_sorted, xq, 'pchip');

Unexpected NaN Values Across Output Arrays

Cause: By default, MATLAB interpolation disables extrapolation. Any query point in xq located strictly below min(x) or strictly above max(x) returns NaN. For scattered data, any query coordinate lying outside the convex hull of the input coordinates returns NaN.

Solution: Verify domain coverage or explicitly pass an extrapolation parameter:

% Option A: Algorithmic extrapolation
vq = interp1(x, v, xq, 'linear', 'extrap');

% Option B: Constant numeric padding (e.g. 0.0)
vq = interp1(x, v, xq, 'linear', 0.0);

% Option C: Check boundary bounds programmatically
out_of_bounds_count = sum(xq < min(x) | xq > max(x));
fprintf('Query points outside sample bounds: %dn', out_of_bounds_count);

Unphysical Oscillations and Negative Values (Runge’s Phenomenon)

Cause: Fitting a high-degree polynomial or unconstrained cubic spline ('spline') across data with flat plateaus followed by sharp steps causes overshoot oscillations. In physical modeling, this can produce unphysical negative concentrations, negative Kelvin temperatures, or negative particle counts.

Solution: Switch from 'spline' to shape-preserving piecewise cubic Hermite interpolation ('pchip') or modified Akima ('makima'). PCHIP mathematically guarantees that no interpolated value exceeds the local minimum or maximum of adjacent sample points:

% Replace spline with pchip to preserve physical positivity
vq_safe = interp1(x, v, xq, 'pchip');

Severe Performance Bottlenecks in Iterative Simulation Loops

Cause: Repeatedly calling interp2(X, Y, V, xq, yq) inside an optimization routine or differential equation integration loop forces MATLAB to re-validate coordinate arrays, reconstruct coordinate trees, and parse arguments on every single iteration.

Solution: Pre-build a persistent griddedInterpolant or scatteredInterpolant object outside the loop and call the handle directly inside the loop:

% Pre-compute interpolant outside the loop
F = griddedInterpolant(X, Y, V, 'linear', 'nearest');

% Fast evaluation inside iterative simulation loop
for iter = 1:10000
    % Dynamic query coordinates calculated during simulation
    xq_current = simulation_state_x(iter);
    yq_current = simulation_state_y(iter);
    vq_current = F(xq_current, yq_current); % Order-of-magnitude faster
    % ... computational update ...
end

Free alternatives

Research teams operating without proprietary MATLAB licenses or aiming to establish fully open-source, containerized reproducible workflows can utilize several mature open-source scientific alternatives offering equivalent interpolation algorithms:

Tool / Environment Key Functions / Modules License MATLAB Syntax Compatibility Key Strengths & Ecosystem Notes
GNU Octave interp1, interp2, interpn, griddata, pchip, spline GPLv3 Direct drop-in compatibility (Identical command signatures and arguments) Executes existing MATLAB .m scripts without code modification. Supports * prefix (e.g. "*linear") for accelerated uniform grid indexing. Returns NA instead of NaN by default for out-of-bounds queries.
Python (SciPy) scipy.interpolate.CubicSpline, PchipInterpolator, RegularGridInterpolator, griddata BSD 3-Clause Algorithmic equivalence; object-oriented Python syntax Modern SciPy provides dedicated classes matching MATLAB methods (CubicSpline matches 'spline', PchipInterpolator matches 'pchip'). Seamlessly connects with NumPy, pandas, and PyTorch for scientific workflows.
Julia Interpolations.jl (interpolate, extrapolate, BSpline) MIT Functional composition syntax High performance compiled via LLVM. Supports zero-allocation in-place evaluations on structured grids, ideal for large-scale physical simulations.
R approx(), spline(), splinefun(), pracma::interp1() GPL-2 / GPL-3 Standard R functional syntax; pracma package emulates MATLAB syntax Base R provides built-in approx (linear) and spline (cubic) functions. Tailored for statistical regression and biological cohort analysis.

For existing MATLAB codebases, GNU Octave represents the most direct migration path, executing identical interp1(x, v, xq, 'pchip') syntax directly in headless terminal scripts or graphical interactive sessions.

FAQ

What is the difference between spline and pchip in MATLAB?

In MATLAB, 'spline' constructs a cubic spline with continuous first and second derivatives (C² continuity). This results in a very smooth curve across all points, but it can oscillate wildly or overshoot near abrupt changes in data slope. In contrast, 'pchip' (Piecewise Cubic Hermite Interpolating Polynomial) enforces C¹ continuity (continuous first derivative only) while strictly preserving local monotonicity. If sample data points are non-decreasing, the PCHIP interpolant is guaranteed never to decrease or create artificial local extrema.

When should I use makima instead of pchip or spline?

Modified Akima interpolation ('makima') is designed for datasets featuring natural wave oscillations or smooth curves where standard cubic splines produce excessive ringing or overshoot, but PCHIP looks overly flattened near local extrema. Makima computes local derivatives by taking a weighted average of neighboring secant slopes, striking an effective balance between smoothness and overshoot suppression.

How do I handle query points outside the sample range in MATLAB?

By default, interp1 and interp2 assign NaN to any query point located outside the domain bounded by [min(x), max(x)]. To extrapolate using the mathematical rule of your chosen method, pass the string 'extrap' as a trailing argument: vq = interp1(x, v, xq, 'linear', 'extrap'). To assign a specific numerical value to all out-of-range points instead, pass a scalar constant: vq = interp1(x, v, xq, 'linear', 0).

Why is griddedInterpolant faster than interp2 for repetitive calculations?

Every time interp2 is called, MATLAB parses argument inputs, validates that coordinates are monotonic, and sets up temporary grid lookup structures. griddedInterpolant pre-computes and caches the grid geometry, triangulation, and indexing data structures once in memory. Subsequent evaluations Vq = F(Xq, Yq) execute substantially faster, making griddedInterpolant the recommended approach for optimization routines and time-stepping differential equation solvers.

How does MATLAB interpolate scattered, unstructured data?

For two-dimensional or multi-dimensional data points that do not fall on an orderly grid, MATLAB uses griddata or the object-oriented scatteredInterpolant. These routines construct a Delaunay triangulation of the input coordinates and evaluate query points using natural neighbor ('natural'), linear, or nearest neighbor algorithms. Query points lying outside the convex hull of the input data return NaN unless nearest-neighbor extrapolation is configured.

Sources

Follow CASRAI

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

Ask CASRAI · free to try

Ask about MATLAB Interpolation: interp1, Gridded Data 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 →