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.comwithout 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).
-
Prepare and Validate Monotonic Sample Points:
Sample points
xmust 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); -
Define Query Coordinates:
Construct a fine query vector
xqspanning 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); -
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'); -
Configure Boundary Extrapolation Behavior:
By default, query points lying outside
[min(x), max(x)]evaluate toNaN. To enable mathematical extrapolation beyond sample bounds, supply'extrap'as the trailing parameter, or provide a scalar constant (such as0) 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); -
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.
-
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); -
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'); -
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.
-
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); -
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'); -
Evaluate Across a Uniform Query Grid:
Generate Cartesian query points using
meshgridand 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
NaNwhen 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
- MathWorks. (2026). 1-D data interpolation (table lookup) – interp1. MathWorks Documentation. Accessed November 9, 2026. https://www.mathworks.com/help/matlab/ref/interp1.html
- MathWorks. (2026). Interpolating Gridded Data. MathWorks Documentation. Accessed November 9, 2026. https://www.mathworks.com/help/matlab/math/interpolating-gridded-data.html
- MathWorks. (2026). Gridded data interpolation – griddedInterpolant. MathWorks Documentation. Accessed November 9, 2026. https://www.mathworks.com/help/matlab/ref/griddedinterpolant.html
- MathWorks. (2026). Interpolate scattered data – griddata. MathWorks Documentation. Accessed November 9, 2026. https://www.mathworks.com/help/matlab/ref/griddata.html
- Moler, C. B. (2004). Numerical Computing with MATLAB (Chapter 3: “Interpolation”). Society for Industrial and Applied Mathematics (SIAM) / MathWorks. Accessed November 9, 2026. https://www.mathworks.com/moler/chapters.html
- GNU Octave. (2026). GNU Octave Manual: Section 29 Interpolation. Free Software Foundation. Accessed November 9, 2026. https://docs.octave.org/latest/Interpolation.html
- SciPy Community. (2026). Interpolation (scipy.interpolate). SciPy Reference Guide v1.14. Accessed November 9, 2026. https://docs.scipy.org/doc/scipy/reference/interpolate.html







