Pearson's Coefficient and Covariance calculation in Matlab

风格不统一 提交于 2019-12-05 05:10:49

I think you're just confused with covariance and covariance matrix, and the mathematical notation and MATLAB's function inputs do look similar. In math, cov(x,y) means the covariance of the two variables x and y. In MATLAB, cov(x,y) calculates the covariance matrix of x and y. Here cov is a function and x and y are the inputs.

Just to make it clearer, let me denote the covariance by C. MATLAB's cov(x,y) returns a matrix of the form

C_xx    C_xy
C_yx    C_yy

As RichC pointed out, you need the off-diagonals, C_xy (note that C_xy=C_yx for real variables x and y). A MATLAB script that gives you the Pearson's coefficient for two variables x and y, is:

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

From the docs:

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

use:

C = cov(X,Y);
coeff = C(1,2) / sqrt(C(1,1) * C(2,2))
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!