问题描述
我想在Matlab中计算皮尔逊相关系数(不使用Matlab的corr
功能).
I want to calculate Pearson's correlation coefficent in Matlab (without using Matlab's corr
function).
简而言之,我有两个向量A和B(每个向量均为1x100),我正在尝试像这样计算皮尔逊系数:
Simply, I have two vectors A and B (each of them is 1x100) and I am trying to calculate the Pearson's coefficient like this:
P = cov(x, y)/std(x, 1)std(y,1)
我正在使用Matlab的cov
和std
函数.我没有得到的是,cov函数返回一个像这样的方阵:
I am using Matlab's cov
and std
functions. What I don't get is, the cov function returns me a square matrix like this:
corrAB =
0.8000 0.2000
0.2000 4.8000
但是我希望有一个单一的数字作为协方差,所以我可以得出一个单一的P(皮尔逊系数)数字.我想念的是什么?
But I expect a single number as the covariance so I can come up with a single P (pearson's coefficient) number. What is the point I'm missing?
推荐答案
我认为您只是对协方差和协方差矩阵感到困惑,而且数学符号和MATLAB的函数输入看起来确实很相似.在数学中,cov(x,y)
表示两个变量的 协方差 x
和y
.在MATLAB中,cov(x,y)
计算x
的 ="a href =" http://en.wikipedia.org/wiki/Covariance_matrix"rel =" noreferrer>协方差矩阵 和y
. cov
是函数,而x
和y
是输入.
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.
为了更清楚一点,让我用C
表示协方差. MATLAB的cov(x,y)
返回格式为
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
正如RichC所指出的,您需要非对角线C_xy
(请注意,对于实变量x
和y
,C_xy=C_yx
).一个为您提供两个变量x
和y
的皮尔逊系数的MATLAB脚本为:
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));
这篇关于Matlab中的Pearson系数和协方差计算的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!