Pearson coefficient and covariance in Matlab

I want to calculate the Pearson correlation coefficient in Matlab (without using the Matlab corr function).

I just have two vectors A and B (each of them is 1x100), and I'm trying to calculate the Pearson coefficient as follows:

 P = cov(x, y)/std(x, 1)std(y,1) 

I use the matlab cov and std functions. What I do not get, the cov function returns me a square matrix as follows:

 corrAB = 0.8000 0.2000 0.2000 4.8000 

But I expect that there will be one number as the covariance, so I can come up with one P coefficient (pearson coefficient). What is the point I miss?

+7
source share
2 answers

I think that you are simply confused with the covariance and covariance matrix, and the mathematical notation and the functional inputs of MATLAB look the same. In mathematics, cov(x,y) means the covariance of two variables x and y . MATLAB cov(x,y) computes the covariance matrix from x and y . Here cov is a function, and x and y are inputs.

To clarify, let me denote covariance in C MATLAB cov(x,y) returns the form matrix

 C_xx C_xy C_yx C_yy 

As RichC noted, you need off-diagonals, C_xy (note that C_xy=C_yx for real variables x and y ). The MATLAB script, which gives you the Pearson coefficient for the two variables x and y , is:

 C=cov(x,y); p=C(2)/(std(x)*std(y)); 
+10
source

From the docs:

cov (X, Y), where X and Y are matrices with the same number of elements, is equivalent to cov ([X (:) Y (:)]).

using:

 C = cov(X,Y); coeff = C(1,2) / sqrt(C(1,1) * C(2,2)) 
+2
source

All Articles