Skip to content
Tutorials Center
My learning

Topics

Lesson 11 of 45 ยท Operators and Math

Built-in Math and Statistics

Summarize data in MATLAB and Octave with sum, cumsum, mean, median, std, max with indices, round, mod and NaN handling, using runnable Python stand-ins.

Once your data sits in a matrix, the next question is almost always "what does it add up to?", "what is typical?" or "where is the biggest value?". MATLAB and Octave answer these with a compact family of functions that all follow the same rule: they work down the columns of a matrix unless you tell them otherwise.

This lesson covers the aggregating functions (sum, prod, cumsum, mean, median, std, var), min and max with their index outputs, the rounding and remainder functions, and how to cope with NaN values. It builds on Reshaping, Joining and Sorting and on masks from Logical Indexing and find.

MATLAB and Octave are not installed on this site, so matlab blocks are read-only. The TryIt blocks are NumPy stand-ins: axis=0 there corresponds to MATLAB's dimension 1 (down the columns) and axis=1 to dimension 2 (along the rows). A few details, such as rounding of .5, differ between the two and are called out.

One rule for dimensions

Dimension 1 Default. One result per column.
Dimension 2 sum(A, 2): one result per row.
All sum(A, 'all') or A(:) collapses everything.

A vector is treated as a single column or row, whichever it is.

1 / 2

Totals along a dimension

Consider weekly sales for three shops, one row per week and one column per shop:

MATLAB
S = [4 8 2;
     6 1 9;
     3 7 5];

sum(S)         % 13 16 16   total per shop (down the columns)
sum(S, 2)      % 14; 16; 15 total per week (along the rows)
sum(S(:))      % 45         everything; also sum(S, 'all') in recent versions
prod([1 2 3 4])   % 24

The cumulative versions return a running total with the same shape as the input:

MATLAB
cumsum(S)       % 4 8 2 ; 10 9 11 ; 13 16 16
cumsum(S, 2)    % 4 12 14 ; 6 7 16 ; 3 10 15
cumprod(1:5)    % 1 2 6 24 120

For a row or column vector you do not need a dimension: sum(1:10) is 55 either way. For a matrix, always think about which dimension you want; forgetting that sum(S) returns a row of three totals instead of one number is a classic slip.

Averages and spread

mean, median and mode describe the center; std, var and max(x) - min(x) describe the spread. mean(S) returns a row of column means and mean(S, 2) a column of row means.

One detail trips up people coming from other tools: std and var divide by N - 1 by default (the sample standard deviation). Pass 1 as the second argument for the population version, std(x, 1), which divides by N.

MATLAB
mean(S)        % 4.3333  5.3333  5.3333
median(S)      % 4  7  5
std(S)         % 1.5275  3.7859  3.5119     divides by N-1
std(S, 1)      % 1.2472  3.0912  2.8674     divides by N
var(S)         % 2.3333  14.3333  12.3333
Python Totals, running totals and statistics

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

NumPy's std divides by N by default, so the stand-in passes ddof=1 to match MATLAB's default and ddof=0 for std(S, 1). Always check the default of a statistics function when you move between languages.

min and max with positions

max has several forms and returns up to two outputs, the value and the position (1-based):

MATLAB
[m, i] = max(S)       % m = 6 8 9,  i = 2 1 2   per column
max(S, [], 2)         % 8; 9; 7                  per row (the [] is a placeholder)
max(S(:))             % 9      overall; or max(S, [], 'all')
[v, k] = max(S(:))    % v = 9, k = 8   k is a linear index
max(S, 5)             % two-argument form: element-wise larger of S and 5

The two-argument form compares element by element and is the idiom for clamping: max(x, 0) replaces negatives with 0 and min(x, 100) caps at 100. If several elements tie, max returns the first one. To convert a linear index into row and column, use [r, c] = ind2sub(size(S), k); see Indexing and Slicing.

Rounding and remainders

MATLAB has four rounding functions. They differ for negative numbers and for halves:

Function Rule -2.5 -1.5 1.5 2.5
round nearest, halves away from zero -3 -2 2 3
floor toward minus infinity -3 -2 1 2
ceil toward plus infinity -2 -1 2 3
fix toward zero -2 -1 1 2

NumPy's own round rounds halves to the nearest even number (2.5 becomes 2), so the stand-in below builds MATLAB's rule by hand. round(x, n) with a digit count is available in recent MATLAB versions.

For remainders, mod(a, m) takes the sign of the divisor and always lands in the range 0 to m, which is what you want for wrap-around such as clock arithmetic and cyclic indices. rem(a, m) takes the sign of the dividend.

MATLAB
mod(-7, 3)    %  2
rem(-7, 3)    % -1
mod(7, -3)    % -2
rem(7, -3)    %  1
mod(5.5, 2)   %  1.5
mod(x, 0)     %  x    (mod with 0 returns the input)
Python Extremes, rounding and mod

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Two other everyday functions deserve a mention: abs and sign, and the exponent and logarithm family exp, log (natural), log10, log2 and sqrt. All of them are element-wise and work on whole arrays.

Dealing with NaN

Missing measurements are stored as NaN. By default most aggregations return NaN as soon as one input is NaN, because the true total is unknown. The notable exceptions are min and max, which ignore NaN values.

MATLAB
d = [7 2 NaN;
     5 NaN 4;
     6 3 8];

sum(d)                    % 18  NaN  NaN
mean(d)                   %  6  NaN  NaN
max(d)                    %  7    3    8     ignores NaN
mean(d, 'omitnan')        %  6  2.5  6      MATLAB; recent Octave also accepts it
sum(d, 'omitnan')         % 18    5  12

Where a function has no 'omitnan' flag (older Octave versions, for example), build the answer from a mask, as in Logical Indexing and find: sum with the NaNs replaced by 0, and divide by sum(~isnan(d)).

Python Totals and means that skip NaN

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

In NumPy the plain functions return nan and the nan-prefixed versions skip missing values, and np.nanmax is needed because NumPy's max propagates NaN, unlike MATLAB's.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. For a 3-by-3 matrix S, what does sum(S) return?

    By default, aggregating functions work down the columns (dimension 1), so you get one total per column. Use sum(S, 2) for rows or sum(S(:)) for everything.
  2. 2. What are the outputs of [m, i] = max([3 9 2 9])?

    max returns the value and the position of the first maximum, using 1-based indexing.
  3. 3. What is std(x) dividing by for a vector of N values?

    The default is the sample standard deviation with N - 1. Use std(x, 1) for the population version that divides by N.
  4. 4. What is mod(-7, 3)?

    mod takes the sign of the divisor, so the result lies between 0 and 3. rem(-7, 3) would give -1.
  5. 5. Given x = [1 NaN 3], which statement is true?

    min and max skip NaN, while sum and mean return NaN unless you ask them to omit missing values.

Summary

  • Aggregating functions work down columns by default; pass a dimension (sum(A, 2)) or use A(:) for everything.
  • cumsum and cumprod keep the input's shape; mean, median, std and var describe center and spread, with std and var using N - 1 by default.
  • [m, i] = max(x) returns the value and a 1-based position; max(A, [], 2) works along rows and max(A, 0) clamps element-wise.
  • round goes half away from zero, floor, ceil and fix differ for negatives, and mod follows the divisor's sign while rem follows the dividend's.
  • NaN spreads through sums and means but not through min and max; use 'omitnan' or a mask to skip it.

Next: see how numbers are stored in Numeric Types and Precision.