TExcelTAD
Home › MATLAB / Octave › Statistics Functions

Statistics Functions

MATLAB's core library includes the descriptive statistics you need for everyday data analysis. Like other reduction functions, they work on vectors, and on matrices column by column unless you pass a dimension.

Central tendency and spread

Function Returns
mean(x) Arithmetic average
median(x) Middle value of the sorted data
mode(x) Most frequent value (smallest one if tied)
std(x) Standard deviation (normalised by N−1)
var(x) Variance, std(x)^2
min(x), max(x) Extremes (and their positions)
range(x) max - min (use max(x) - min(x) for portability)
matlab · try it yourself
waits = [4 7 2 9 7 3 12 7 5 6];      % minutes waited at a bus stop
fprintf('mean   %.2f\n', mean(waits));
fprintf('median %.2f\n', median(waits));
fprintf('mode   %d\n', mode(waits));
fprintf('std    %.4f\n', std(waits));
fprintf('var    %.4f\n', var(waits));
[lo, iLo] = min(waits);
[hi, iHi] = max(waits);
fprintf('min %d (day %d), max %d (day %d), range %d\n', lo, iLo, hi, iHi, hi - lo);
mean   6.20
median 6.50
mode   7
std    2.9364
var    8.6222
min 2 (day 3), max 12 (day 7), range 10

The median is less sensitive to outliers than the mean: a single 60-minute wait would move the mean a lot but the median hardly at all.

Sample vs population standard deviation

std(x) divides by N−1 (the sample standard deviation, an unbiased estimate when your data is a sample). Pass 1 as the second argument to divide by N (the population standard deviation):

matlab · try it yourself
x = [2 4 4 4 5 5 7 9];
fprintf('std, N-1:       %.4f\n', std(x));
fprintf('std, N:         %.4f\n', std(x, 1));
fprintf('by hand:        %.4f\n', sqrt(sum((x - mean(x)).^2) / numel(x)));
std, N-1:       2.1381
std, N:         2.0000
by hand:        2.0000

Statistics of matrices

Each column is treated as a separate variable. Use the dimension argument for rows. Note that for std, var, min and max the dimension is the third argument:

matlab · try it yourself
% rows = 4 days, columns = 3 weather stations (temperature)
T = [12.1 14.3 11.8
     13.5 15.0 12.2
     11.9 13.8 12.9
     14.2 16.1 13.1];
disp(mean(T))             % per station
disp(mean(T, 2)')         % per day
disp(std(T, 0, 1))        % per station: weights 0 (N-1), dimension 1
disp(max(T, [], 2)')      % warmest reading each day
   12.925   14.800   12.500
   12.733   13.567   12.867   14.467
   1.1087   0.9967   0.6055
   14.300   15.000   13.800   16.100

max(T, [], 2) needs the empty [] placeholder because max(T, 2) means "compare each element with 2".

Missing data

NaN values poison most calculations: any sum including a NaN is NaN. Pass 'omitnan' to ignore them (min and max ignore NaN automatically):

matlab · try it yourself
r = [4.2 NaN 3.9 4.4 NaN 4.0];
fprintf('mean: %g\n', mean(r));
fprintf('mean omitnan: %.3f\n', mean(r, 'omitnan'));
fprintf('max: %g\n', max(r));
fprintf('valid values: %d of %d\n', sum(~isnan(r)), numel(r));
mean: NaN
mean omitnan: 4.125
max: 4.4
valid values: 4 of 6

Sorting and cumulative functions

Function Returns
sort(x), sort(x, 'descend') Sorted values and (second output) original positions
sortrows(A, col) Rows sorted by a column (negative column = descending)
cumsum, cumprod Running sum / product
cummax, cummin Running maximum / minimum
diff Differences between neighbours
matlab · try it yourself
sales = [120 95 140 80 160];
fprintf('cumulative: %s\n', mat2str(cumsum(sales)));
fprintf('best so far: %s\n', mat2str(cummax(sales)));
fprintf('change: %s\n', mat2str(diff(sales)));

results = [101 72; 102 91; 103 85; 104 91];   % [id score]
ranked = sortrows(results, -2)
cumulative: [120 215 355 435 595]
best so far: [120 120 140 140 160]
change: [-25 45 -60 80]
ranked =

   102    91
   104    91
   103    85
   101    72

sortrows keeps ties in their original order (102 before 104), so you can sort by a secondary key first and then by the primary one.

Correlation and counting

corrcoef returns the correlation matrix of two variables (the off-diagonal element is the correlation coefficient, between −1 and 1). histc counts values in bins, and accumarray sums values per group:

matlab · try it yourself
hours = [1 2 3 4 5 6];
score = [52 55 61 64 70 74];
R = corrcoef(hours, score);
fprintf('correlation: %.4f\n', R(1, 2));

ages = [23 35 41 29 52 38 61 27];
counts = histc(ages, [20 30 40 50 60 70]);
disp(counts(1:end-1))       % how many in 20-29, 30-39, 40-49, 50-59, 60-69

group = [1 2 1 3 2 1];
amount = [10 5 20 7 15 30];
disp(accumarray(group', amount')')
correlation: 0.9962
   3   2   1   1   1
   60   20    7

histc returns one extra count at the end for values exactly equal to the last edge, which is why the code drops it.

Test yourself

What is median([7 1 9 3])?

  1. 5
  2. 3
  3. 7
  4. 4

How do you compute the mean of x while ignoring NaN values?

  1. mean(x, 'skip')
  2. mean(x, 'omitnan')
  3. nanmean(x) only
  4. mean(x(~x))

Why does max(A, [], 2) contain []?

  1. It is a typo
  2. Because max(A, 2) would compare A with 2 element-wise
  3. To ignore NaN
  4. To return the indices