Open In App

How to Calculate Variance in MATLAB?

Last Updated : 19 Oct, 2022
Improve
Improve
Like Article
Like
Save
Share
Report

Pre-requisites: Calculate Variance

In statistical mathematics, Variance is the measure of dispersion of a given data from its average value. This is a very important quantity in statistics and many other fields like Machine Learning and AI. 

Variance in MATLAB:

MATLAB provides a simple function to calculate the variance of a given data, the var() function. 

Syntax:

variance = var(<data>, <weight>, …)

Here, the <data> is a vector or array of data, and <weight> is an optional argument used for weighted data.

Let’s see the usage of var with some examples.

Example 1:

Matlab




% MATLAB code for Calculating the 
% variance of a 1D vector [23:75].
% Creating a vector 
    data = 23:75;
  
% Calculating variance
  variance = var(data);
  disp(variance)


Output:

 

The calculated variance is 238.50, which can be verified manually.

Calculating variance of weighted data. We use the same vector but, just add another vector which stores the weight of every element in the data. 

Example 2:

Matlab




% MATLAB code for creating a vector and weights
  data = 23:75;
  w=linspace(3,13,53);
  
%calculating variance
 variance = var(data,w);
 disp(variance)


Output:

This will give, us the weighted variance of the user data and weights.

 

We can also calculate the variance of a multidimensional vector along a particular dimension (less than the maximum dimension) as follows.

Example 3:

Matlab




% MATLAB code forcreating a vector and weights
  data = [1 3 -2; 2 3 7; 0 4 2.1];
  
% w = [0.1, 3, 2.1];
% Calculating variance at all dimensions
  var(data,0,"all")
  
% Calculating variance at 1st dimension
  var(data,0,1)
  
% Calculating variance at 2nd dimension
  var(data,0,2)


Output:

 

Conclusion:

This article discussed various ways of calculating variance in MATLAB for different kinds of data.



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

Similar Reads