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

MATLAB Average Function: mean, Arrays & NaN Guide

Learn how to use the MATLAB average function mean across vectors, matrices, and multidimensional arrays, including omitnan filtering and weighted averages.

Written and maintained by CASRAI Editorial Board

Published

On this page

In MATLAB, there is no built-in function named average(). Researchers and programmers coming from spreadsheets or other environments frequently search for an average command, but in MATLAB the arithmetic average is computed using the built-in mean() function. The mean() function operates across vectors, two-dimensional matrices, and multidimensional arrays, offering specialized parameters for dimensional reductions, missing data filtering with "omitnan", and weighted averages.

What it is used for in research

Computing the arithmetic average is a fundamental operation across scientific computing, observational data analysis, and numerical modeling. Researchers regularly apply the mean() function to aggregate repeated experimental measurements, normalize physiological signals, summarize longitudinal cohorts, and reduce multi-axis simulation meshes into lower-dimensional summaries.

Key applications of the average and mean function in research workflows include:

  • Experimental Measurement Aggregation: Calculating central tendencies across technical replicates, laboratory assays, or sensor trials while computing variance metrics alongside standard deviation in MATLAB.
  • Multidimensional Grid Reductions: Collapsing spatial dimensions in three-dimensional neuroimaging scans, climate models, or finite element grids using vector dimension arguments.
  • Signal Baseline Centering: Subtracting channel-wise means from raw digitized sensor traces to eliminate DC offsets prior to spectral or wavelet transforms.
  • High-Throughput Matrix Operations: Replacing manual accumulator loops with vectorized array operations in MATLAB to process entire data tables and multidimensional tensors efficiently.

Average function matlab in quantitative research

When developing automated data pipelines, understanding how MATLAB computes averages across array dimensions prevents subtle calculation errors. Unlike scalar-only scripting environments, MATLAB treats arrays as first-class citizens. For time-series analysis with local rolling windows, researchers combine global averages with MATLAB moving average filtering using movmean(). In structured analytical routines and published codebases, embedding robust mean operations ensures computational reproducibility in MATLAB script and function development.

Install or access (official source only)

The mean() function is a core built-in component of base MATLAB and does not require any additional toolboxes (such as the Statistics and Machine Learning Toolbox). It is accessible through official MathWorks distributions:

  • MATLAB Desktop: Installed on Windows, macOS, or Linux through an authorized MathWorks Account via the official MathWorks installer.
  • MATLAB Online: Accessed directly via supported modern web browsers through the MathWorks cloud platform at matlab.mathworks.com.
  • MATLAB Mobile: Connected via official mobile applications for iOS and Android linked to a licensed MathWorks cloud or desktop session.
  • Local Documentation: Accessed within the MATLAB Command Window by executing doc mean for the full interactive documentation browser or help mean for immediate console syntax summaries.

Step-by-step task (numbered, with menu names or commands exactly as in the current docs)

Follow these numbered steps to calculate averages across different array geometries, filter missing values, and compute weighted averages in the MATLAB Command Window or Editor.

  1. Calculate the average of a 1D vector:

    Define a row or column vector and pass it to mean() to compute the scalar arithmetic mean:

    % Define a vector of experimental measurements
    v = [12.4, 15.8, 14.2, 18.1, 16.5];
    
    % Compute the scalar average
    avg_val = mean(v);
    % Returns: avg_val = 15.4000
  2. Calculate column-wise and row-wise averages in a 2D matrix:

    By default, calling mean(A) on a matrix computes averages along dimension 1 (down each column). To compute row-wise averages, specify dimension 2 (mean(A, 2)):

    % Create a 3x4 matrix (3 observations across 4 variables)
    A = [10, 20, 30, 40;
         12, 22, 32, 42;
         14, 24, 34, 44];
    
    % Column averages (dim 1, default): returns 1x4 row vector
    col_avg = mean(A);
    % Returns: [12, 22, 32, 42]
    
    % Row averages (dim 2): returns 3x1 column vector
    row_avg = mean(A, 2);
    % Returns: [25; 27; 29]
  3. Compute the overall grand average across all elements:

    To calculate the single average of all elements in a matrix or multidimensional array, use the "all" flag (or colon vectorization A(:)):

    % Compute grand mean over all elements of the matrix
    grand_avg = mean(A, "all");
    % Returns: grand_avg = 27
  4. Average across specific dimensions in a 3D array:

    When working with volumetric or multi-channel scientific data, pass a vector of dimensions (vecdim) to average across specific slices:

    % Simulate a 3D dataset: 100 spatial rows x 100 spatial cols x 12 timepoints
    sensor_cube = rand(100, 100, 12);
    
    % Average over spatial dimensions [1 2] to obtain a 1x1x12 temporal mean profile
    temporal_profile = mean(sensor_cube, [1, 2]);
    
    % Squeeze singleton dimensions to yield a clean 12x1 vector
    temporal_vector = squeeze(temporal_profile);
  5. Exclude missing values (NaN) with omitnan:

    By default, MATLAB propagates NaN values, causing the output to evaluate to NaN if any element is undefined. Specify "omitnan" to exclude missing values from the calculation:

    % Vector containing unrecorded experimental samples
    raw_samples = [4.2, 5.1, NaN, 6.3, NaN, 5.9];
    
    % Standard mean returns NaN
    bad_avg = mean(raw_samples);
    % Returns: bad_avg = NaN
    
    % Exclude NaN values from the numerator and denominator count
    clean_avg = mean(raw_samples, "omitnan");
    % Returns: clean_avg = 5.3750
  6. Compute a weighted arithmetic average:

    To assign non-uniform importance or sample variances to observations, use the 'Weights' name-value argument:

    % Measurement values and their corresponding sample weights
    vals = [80, 90, 70];
    weights = [1, 2, 1];
    
    % Compute weighted mean: (80*1 + 90*2 + 70*1) / (1 + 2 + 1) = 330 / 4
    w_avg = mean(vals, "Weights", weights);
    % Returns: w_avg = 82.5000

Output and how to read it

The output of mean() depends on the input data structure, the operating dimension, and specified options:

  • Scalar Outputs: When evaluating a 1D vector or when passing "all", mean() returns a single scalar value.
  • Dimensional Reduction: When operating along dimension dim, that dimension is reduced to length 1. For an M × N matrix, mean(A, 1) yields a 1 × N row vector, while mean(A, 2) yields an M × 1 column vector.
  • Data Types and Precision: By default ('default'), inputs of type double return double, while inputs of type single return single. Integer inputs (such as uint8 or int32) and logical arrays evaluate to double by default to prevent integer rounding loss during division. If 'native' is specified, the output is rounded to match the input integer class.
  • Missing Values (NaN): Under default "includenan" behavior, any NaN in the operating slice results in a NaN output. When "omitnan" is set, NaN values are omitted from both the sum and the element count N; if an entire slice consists solely of NaN values, the output remains NaN.

Troubleshooting

Researchers commonly encounter specific syntax or numerical issues when computing averages in MATLAB. Use the diagnostic solutions below to resolve them.

Undefined function ‘average’ for input arguments

Issue: Running average(x) produces the error Undefined function 'average' for input arguments of type 'double'.
Fix: MATLAB does not include an average() function. Replace average(x) with mean(x) for arithmetic means, or movmean(x, k) for moving averages.

Why does mean return NaN?

Issue: The calculated average outputs NaN even if only one missing data point exists.
Fix: Base MATLAB uses "includenan" by default. Add the "omitnan" flag to your function call: mean(data, "omitnan"). Note that the legacy function nanmean() from the Statistics Toolbox is deprecated in favor of mean(..., "omitnan").

Why does mean of a matrix return a row vector instead of a single number?

Issue: Passing a 2D matrix A into mean(A) returns multiple numbers (a row vector) instead of the total overall average.
Fix: In MATLAB, mean(A) reduces along dimension 1 (column-by-column). To obtain the overall scalar average across all rows and columns, execute mean(A, "all") or mean(A(:)).

Unexpected integer rounding or truncation with native types

Issue: Calling mean(A, 'native') on integer data (such as image pixel arrays of type uint8) returns unexpected integer values or rounds down.
Fix: Omit the 'native' parameter so MATLAB uses default double precision for division, or convert the array prior to calculation using double(A).

Free alternatives (table)

Researchers seeking open-source software alternatives to MATLAB have several mature options across scientific computing languages. The table below compares base MATLAB with GNU Octave, Python NumPy, R, and Julia.

Software License & Ecosystem 1D Vector Mean Syntax 2D Matrix Reduction Syntax Missing Data Handling (NaN) Research Strengths
MATLAB Proprietary (MathWorks) mean(x) mean(A, 1) (cols)
mean(A, 2) (rows)
mean(A, "all")
mean(x, "omitnan") Integrated engineering toolboxes, interactive Live Editor, optimized multi-threading.
GNU Octave Open Source (GNU GPL v3) mean(x) mean(A, 1) (cols)
mean(A, 2) (rows)
mean(A, "all")
mean(x, "omitnan") Direct drop-in syntax compatibility with MATLAB scripts; zero porting effort.
Python (NumPy) Open Source (BSD 3-Clause) np.mean(x) np.mean(A, axis=0)
np.mean(A, axis=1)
np.mean(A) (all)
np.nanmean(x) Massive open-source ecosystem, PyTorch/SciPy integration, deep learning pipelines.
R Open Source (GNU GPL v2+) mean(x) colMeans(A)
rowMeans(A)
mean(A)
mean(x, na.rm=TRUE) Exceptional statistical modeling library, CRAN packages (see MATLAB vs R).
Julia Open Source (MIT License) Statistics.mean(x) mean(A, dims=1)
mean(A, dims=2)
mean(A) (all)
mean(skipmissing(x)) High-performance just-in-time compilation; native mathematical syntax and speed.

FAQ

Does MATLAB have an average() function?

No. MATLAB does not contain a built-in function named average(). Attempting to call average(x) results in an undefined function error. In MATLAB, the arithmetic mean is computed using the built-in mean() function.

How do I calculate the average of an entire matrix or multidimensional array?

To calculate the average of all elements in a matrix or multidimensional array, use mean(A, "all") (introduced in R2018b) or flatten the array into a column vector using colon notation: mean(A(:)). Both methods return a single scalar value representing the grand mean.

How do I ignore NaN values when calculating an average in MATLAB?

Pass the string flag "omitnan" as an argument: mean(A, "omitnan"). This instructs MATLAB to exclude missing values from the summation and compute the mean using only valid numeric observations. The older standalone function nanmean() is deprecated.

What is the difference between mean and movmean in MATLAB?

The mean() function computes a static central tendency across an entire array or along a specified dimension, returning a reduced dimension. In contrast, movmean() computes a sliding-window moving average over time-series or sequential data, returning an array with the same length as the original input.

How do I compute a weighted average in MATLAB?

You can compute a weighted average directly using the 'Weights' name-value argument: mean(x, "Weights", w). Alternatively, you can compute it mathematically via vectorized element-wise multiplication: sum(w .* x) / sum(w), ensuring that weights and data share identical dimensions.

Sources (official docs)

Follow CASRAI

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

Ask CASRAI · free to try

Ask about MATLAB Average Function: mean, Arrays & NaN 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 →