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 meanfor the full interactive documentation browser orhelp meanfor 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.
-
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 -
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] -
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 vectorizationA(:)):% Compute grand mean over all elements of the matrix grand_avg = mean(A, "all"); % Returns: grand_avg = 27 -
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); -
Exclude missing values (NaN) with omitnan:
By default, MATLAB propagates
NaNvalues, causing the output to evaluate toNaNif 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 -
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, whilemean(A, 2)yields an M × 1 column vector. - Data Types and Precision: By default (
'default'), inputs of typedoublereturndouble, while inputs of typesinglereturnsingle. Integer inputs (such asuint8orint32) and logical arrays evaluate todoubleby 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, anyNaNin the operating slice results in aNaNoutput. When"omitnan"is set,NaNvalues are omitted from both the sum and the element count N; if an entire slice consists solely ofNaNvalues, the output remainsNaN.
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)
- MathWorks. MATLAB Function Reference: mean (Average or mean value of arrays). URL: https://www.mathworks.com/help/matlab/ref/mean.html (checked 2026-11-11).
- GNU Octave. GNU Octave Manual: Section 27.1 Descriptive Statistics (mean). URL: https://docs.octave.org/latest/Descriptive-Statistics.html (checked 2026-11-11).
- NumPy Developers. NumPy Reference: numpy.mean. URL: https://numpy.org/doc/stable/reference/generated/numpy.mean.html (checked 2026-11-11).
- MIT OpenCourseWare. Numerical Computation for Chemical Engineers: MATLAB Tutorial Chapter 1 – Basic Operations. URL: https://web.mit.edu/10.34/www/MATLAB_tutorial_ch1.html (checked 2026-11-11).







