Open In App

How to Calculate Covariance in MATLAB

Covariance is the measure of the strength of correlation between two or more random variables. Covariance of two random variables X and Y can be defined as:



Where E(X) and E(Y) are expectation or mean of random variables X and Y respectively.

The covariance matrix of two random variables A and B is defined as



MATLAB language allows users to calculate the covariance of random variables using cov() method. Different syntax of cov() method are:

  1. C = cov(A)
  2. C = cov(A,B)
  3. C = cov(___,w)
  4. C = cov(___,nanflag)

C = cov(A)

                              

Note: disp (x) displays the value of variable X without printing the variable name. Another way to display a variable is to type its name, which displays a leading “X =” before the value. If a variable contains an empty array, disp returns without displaying anything.

Example 1:

% Input vector
A = [1 3 4];
disp("Vector :");
disp(A);
 
% Variance of vector A
C = cov(A);
disp("Variance :");
disp(C);

                    

 
 

Output :


 


 

Example 2:


 

% Input vector
A = [2 7 1;
     3 5 1
     4 1 2];
disp("Matrix :");
disp(A);
 
% Covariance of matrix A
C = cov(A);
disp("Covariance matrix :");
disp(C);

                    

 
 

Output :


 

C = cov(A,B)

Example:


 

% Input vector
A = [3 5 7];
B = [-1 3 9];
disp("Vector A:");
disp(A);
disp("Vector B:");
disp(B);
 
% Covariance of vectors A,B
C = cov(A,B);
disp("Covariance matrix :");
disp(C);

                    

 
 

Output :


 

C = cov(___,w)


 

Example:


 

% Input vector
A = [2 4 6;
     3 5 7
     8 10 12];
disp("Matrix :");
disp(A);
 
% Variance of matrix A
C = cov(A,1);
disp("Variance matrix:");
disp(C);

                    

 
 

Output :


 

C = cov(___,nanflag)


 

Example:


 

% Input vector
A = [3.2 -1.005 2.98;
     NaN  -6.75  NaN;
     5.37  0.19  1]
disp("Matrix :");
disp(A);
 
% Variance of matrix A
C = cov(A,'includenan');
disp("Variance matrix including NaN:");
disp(C);
 
 
% Variance of matrix A
C = cov(A,'omitrows');
disp("Variance matrix omitting NaN:");
disp(C);

                    

 
 

Output :


 


 


Article Tags :