Open In App

How to Calculate Harmonic Mean in MATLAB?

Last Updated : 21 Nov, 2022
Improve
Improve
Like Article
Like
Save
Share
Report

Harmonic mean is a type of mean, which is a measure of central tendencies of data, in statistics that gives large weightage to smaller data and small weightage to larger data. The Harmonic Mean in mathematical terms is nothing but the reciprocal of the mean of reciprocal values of all the data elements. 

Harmonic Mean in MATLAB:

MATLAB provides a built-in function to calculate the harmonic mean of a given data, whether it is in form of a vector or an N-dimensional matrix. 

Syntax:

harm_mean = harmmean(<data>, <dimension>)

The <data> could be a vector or an N-dimensional matrix and the <dimension> is an optional argument that specifies the dimension along which the harmonic mean is to be calculated; the <dimension> argument is used only in vectors/matrices of dimensions greater than 1.

Let us understand the usage of the harm mean function with the help of examples.

Example 1 :

Matlab




% Calculating the harmonic mean of a vector in MATLAB
% Creating a vector
vec = 23:45;
 
% Calculating the harmonic mean
harm_mean = harmmean(vec);


Output:

 

Example 2:

Matlab




% Calculating the harmonic mean of a
% 2D matrix along all columns in MATLAB
% Creating a 2D matrix
vec = [-1 23 5;
        3 5 23;
        4 7 13];
         
% Calculating the harmonic mean along all columns
harm_mean = harmmean(vec);


Output:

 

Example 3:

Matlab




% Calculating harmonic mean along a
% specific dimension of an N-D array
% Creating a 5 by 2 by 5 array with elements from 26 to 75
vec = reshape(26:75,[5,2,5]);
 
% Calculating the harmonic mean along 3rd dimension
harm_mean = harmmean(vec,3);
disp(harm_mean)
 
% Calculating the harmonic mean along 1st dimension
harm_mean = harmmean(vec,1);
disp(harm_mean)


Output:

This would give us the harmonic mean along the 3rd dimension and 1st dimension and it would display the same as follows:

 

MATLAB also allows the calculation of the harmonic mean with all elements of multidimensional arrays.

Example 4:

Matlab




% MATLAB code for
% creating a 5 by 2 by 5 array
% with elements from 26 to 75
vec = reshape(26:75,[5,2,5]);
 
% calculating the harmonic mean with all elements
harm_mean = harmmean(vec,"all");


Output:

 



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads