Find a Guide

Statistical Functions in MATLAB for Matrices

Introduction

In a previous tutorial, Statistical Functions in MATLAB for Arrays, we learned about how to use statistical functions built into MATLAB for arrays. These same functions can be applied to matrices as well. Let's start looking at a few!

max()

Let's define a matrix and see what happens when we use the max() function on it.

matlab

mat = [ 4 8 2
             9 1 3
             5 4 6 ];

max(mat)
% output: 9 8 6

By using the max() function on a matrix without any other inputs, MATLAB will take the max of each column. Now if we wanted to take the max of each row, we can do the following:

matlab

% from before
mat = [ 4 8 2
             9 1 3
             5 4 6 ];

max(mat, [], 2)
% output: 8 
%              9 
%              6

The [] in the second input denotes the maximum is being looked for in a specific dimension, and the 2 in the third input is to denote the horizontal dimension. The default is a 1 and that is the vertical dimension, or along columns. If you want to find the overall maximum value of a matrix, you can use the "all" option instead of specifying a direction.

matlab

% from before
mat = [ 4 8 2
             9 1 3
             5 4 6 ];

max(mat, [], "all")
% output: 9 

Notice "all" was used instead of 1 or 2 to find the overall maximum value in the matrix.

min()

The min() function works very similarly to the max() function.

matlab

% from before
mat = [ 4 8 2
             9 1 3
             5 4 6 ];

min(mat)
% output: 4 1 2

min(mat, [], 2)
% output: 2 
%              1 
%              4

min(mat,[],"all")
% output: 1

Notice the notation is the same for the max and min function to access the row and column minimum values as well as the overall minimum.

mean()

To find the mean of a matrix in the row and column dimensions, we can use the mean() function and change the dimension number to get the mean of the columns vs the rows. The column mean corresponds to the number 1 and the row mean corresponds to the number 2.

matlab

% from before
mat = [ 4 8 2
             9 1 3
             5 4 6 ];

mean(mat)
% output: 6 4.3333 3.6667

mean(mat,2)
% output: 4.6667
%              4.3333
%              5

sum()

The last statical function that we'll talk about is the sum() function. The sum notation is very similar to the mean notation. Let's take a look how it works.

matlab

% from before
mat = [ 4 8 2
             9 1 3
             5 4 6 ];

sum(mat)
% output: 18 13 11

sum(mat,2)
% output: 14
%              13
%              15

All of these built-in functions are very useful, especially for analysis of data!

Find a Guide