Open In App

Mean Function in MATLAB

Mean or average is the average of a sequence of numbers. In MATLAB, mean (A) returns the mean of the components of A along the first array dimension whose size doesn’t equal to 1. Suppose that A is a vector, then mean(A) returns the mean of the components. Now, if A is a Matrix form, then mean(A) returns a row vector containing the mean of every column.

Mean  



Example:

Mean of sequence x = [1,2,3,4,5]  = Sum of numbers/Count of numbers

                                                  = 15/5



                                                  = 3

Different syntax of the mean() method is:

 M = mean(A)

Example:

% Input vector
A = [1 2 3 4 5];
disp("Vector :");
disp(A);
 
% Find mean of vector
x = mean(A);
disp("Mean :");
disp(x);

                    

 

 

Output:


 


 

Example:


 

% Input matrix
A = [1 1 2; 2 3 2; 0 1 2; 1 5 7];
disp("Matrix :");
disp(A);
 
% Find mean of matrix
x = mean(A);
disp("Mean :");
disp(x);

                    

Output :

M = mean(A, ‘all’)

It returns the mean of all the elements in A either it can be vector or matrix.

Example:

% Input matrix
A = [1 1 2; 2 3 2; 0 1 2; 1 5 7];
disp("Matrix :");
disp(A);
 
% Find mean of whole matrix
x = mean(A,'all');
disp("Mean :");
disp(x);

                    

Output :

M = mean(A,dim)

Example:

% Input matrix
A = [1 1 2; 2 3 2; 0 1 2; 1 5 7];
disp("Matrix :");
disp(A);
 
% Find mean of each row in matrix
x = mean(A,2);
disp("Mean :");
disp(x);

                    

Output :

M = mean(A,vecdim)

Example:

% Creating a 2-by-3-by-3 array
A(:,:,1) = [12 2; -1 1];
A(:,:,2) = [3 13; -2 10];
A(:,:,3) = [4 7 ; 3 -3];
disp("Array :");
disp(A);
 
% Calculate mean of each page
M1 = mean(A,[1 2]);
disp("Mean of each page :");
disp(M1);

                    

Output:


Article Tags :