Skip to content

MATLAB - Mean Function

In MATLAB, the mean function is an essential tool for descriptive statistics, allowing you to quickly calculate the average (arithmetic mean) of numerical data. Whether you’re a data scientist summarizing experimental results, an engineer analyzing sensor signals, or a financial analyst tracking stock performance, mean is a cornerstone of data analysis.

This tutorial will guide you through its modern syntax and demonstrate its application on various data structures, including vectors, matrices, and tables, with a focus on real-world scenarios like handling missing data.

The syntax for the mean function is flexible and powerful:

M = mean(A) % Calculates the mean of a vector, or column-wise mean for a matrix.
M = mean(A, 'all') % Calculates the mean of all elements in array A.
M = mean(A, dim) % Calculates the mean along a specific dimension `dim`.
M = mean(A, vecdim) % Calculates the mean over the dimensions specified in vector `vecdim`.
M = mean(___, nanflag) % Specifies how to treat NaN (Not-a-Number) values.
  • A: The input data, which can be a vector, matrix, or a multidimensional array. It can also be a table or timetable.
  • 'all': A flag to compute the mean over all elements of A, returning a single scalar value. An alternative is to use mean(A(:)).
  • dim / vecdim: Specifies the dimension(s) to operate along. For a 2D matrix, dim=1 computes the mean down each column, and dim=2 computes the mean across each row.
  • nanflag: A crucial option for real-world data. It can be set to either:
    • "omitnan": Ignores NaN values in the calculation (highly recommended for datasets with missing entries).
    • "includenan": Includes NaN values, which results in NaN if any are present in the calculation slice (the default behavior).

Let’s start with a simple list of exam scores.

% A vector of student scores
scores = [85, 92, 78, 89, 95];
% Calculate the average score
average_score = mean(scores);
fprintf('The average score is: %.2f\n', average_score);
% --- Output ---
% The average score is: 87.80

For a matrix, mean by default operates on each column independently. You must specify the dimension to calculate row-wise means or the overall mean.

% Matrix of student scores (rows are students, columns are assignments)
studentScores = [90, 85, 75; % Student 1
78, 92, 88; % Student 2
81, 89, 94]; % Student 3
% Mean score for each assignment (mean of each column, dim=1 is default)
meanPerAssignment = mean(studentScores, 1);
% Mean score for each student (mean of each row, dim=2)
meanPerStudent = mean(studentScores, 2);
% Overall class average (mean of all elements)
overallMean = mean(studentScores, 'all');
disp('Mean score per assignment:');
disp(meanPerAssignment);
disp('Mean score per student:');
disp(meanPerStudent);
fprintf('Overall class average: %.2f\n', overallMean);
% --- Output ---
% Mean score per assignment:
% 83.0000 88.6667 85.6667
%
% Mean score per student:
% 83.3333
% 86.0000
% 88.0000
%
% Overall class average: 86.00

Real-world data is often messy and contains missing values, represented in MATLAB as NaN (Not-a-Number). By default, mean will return NaN if it encounters one. The 'omitnan' flag is the modern solution.

% Sensor readings, with one missing value
sensorData = [22.5, 23.1, NaN, 22.8, 24.0];
% Default behavior (produces NaN)
meanWithNaN = mean(sensorData);
% Correct way to handle missing data
meanOmitNaN = mean(sensorData, 'omitnan');
fprintf('Mean with NaN included: %.2f\n', meanWithNaN);
fprintf('Mean with NaN omitted: %.2f\n', meanOmitNaN);
% --- Output ---
% Mean with NaN included: NaN
% Mean with NaN omitted: 23.10

In modern data analysis, data is often stored in tables. You can apply mean directly to table variables.

% Create a table with product sales data
products = {'A'; 'B'; 'C'; 'A'; 'B'};
unitsSold = [150; 220; 80; 180; NaN];
salesData = table(products, unitsSold);
disp('Original Sales Data:');
disp(salesData);
% Calculate the mean of the 'unitsSold' column, ignoring the missing value
averageUnitsSold = mean(salesData.unitsSold, 'omitnan');
fprintf('\nAverage units sold: %.2f\n', averageUnitsSold);
% --- Output ---
% Original Sales Data:
% products unitsSold
% ________ _________
%
% {'A'} 150
% {'B'} 220
% {'C'} 80
% {'A'} 180
% {'B'} NaN
%
% Average units sold: 157.50

If your mean calculation unexpectedly returns NaN, it’s almost certain that your input data contains one or more NaN values. Use the 'omitnan' flag to fix this. To locate the NaN values for further inspection, you can use the isnan function: find(isnan(A)).