MATLAB - Mean Function
MATLAB - The mean Function
Section titled “MATLAB - The 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.
Modern Syntax
Section titled “Modern Syntax”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.Key Arguments
Section titled “Key Arguments”A: The input data, which can be a vector, matrix, or a multidimensional array. It can also be atableortimetable.'all': A flag to compute the mean over all elements ofA, returning a single scalar value. An alternative is to usemean(A(:)).dim/vecdim: Specifies the dimension(s) to operate along. For a 2D matrix,dim=1computes the mean down each column, anddim=2computes the mean across each row.nanflag: A crucial option for real-world data. It can be set to either:-
"omitnan": IgnoresNaNvalues in the calculation (highly recommended for datasets with missing entries).
-
"includenan": IncludesNaNvalues, which results inNaNif any are present in the calculation slice (the default behavior).
Examples of the mean() Function
Section titled “Examples of the mean() Function”Example 1: Mean of a Vector
Section titled “Example 1: Mean of a Vector”Let’s start with a simple list of exam scores.
% A vector of student scoresscores = [85, 92, 78, 89, 95];
% Calculate the average scoreaverage_score = mean(scores);
fprintf('The average score is: %.2f\n', average_score);
% --- Output ---% The average score is: 87.80Example 2: Mean Along Matrix Dimensions
Section titled “Example 2: Mean Along Matrix Dimensions”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.00Example 3: Handling Missing Data with NaN
Section titled “Example 3: Handling Missing Data with NaN”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 valuesensorData = [22.5, 23.1, NaN, 22.8, 24.0];
% Default behavior (produces NaN)meanWithNaN = mean(sensorData);
% Correct way to handle missing datameanOmitNaN = 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.10Example 4: Calculating Mean from a Table
Section titled “Example 4: Calculating Mean from a Table”In modern data analysis, data is often stored in tables. You can apply mean directly to table variables.
% Create a table with product sales dataproducts = {'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 valueaverageUnitsSold = 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.50Pro Tip: Debugging with mean
Section titled “Pro Tip: Debugging with mean”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)).