0

是否有等效于 Matlab 的二维相关系数的函数?我想在 2 个一维数组上使用它。 http://www.mathworks.com/help/toolbox/images/ref/corr2.html

编辑:我自己的实现

//Assume we have the length and averages of both arrays
//double a_average, b_average
double a_val =0;
double b_val = 0;
double a_sum = 0 ;
double b_sum = 0;
double a_stdev = 0;
double b_stdev  = 0;
int size = a.length; // same as b's length
for (int i = 0 ; i < size ; i ++) {
    a_val =(a[i]- a_average);
    b_val =(b[i] -b_average);
    a_sum += a_val;
    b_sum += b_val;
    a_stdev += Math.pow(a_val,2);
    b_stdev += Math.pow(b_val,2);
}

double coefficient = ((a_sum *b_sum)/(a_stdev*b_stdev))

谢谢

4

1 回答 1

0

假设您的所有数据都已加载到两个数组A and B中,您要做的是以下内容。此外,假设您的两个数组长度相等并且没有 NaN 和 Infinity 值。

此外,由于您只有两个数据点,因此您的相关矩阵仅包含一个非对角线值,因此我将其存储为单个双精度值。

int i;
int len = A.length;
double correlation;
double XX = 0; //normally would be an outer-product matrix
double[] runningSum = new double[2]; //since you have two variables (A and B)
double[] x2 = new double[2];
double[] stdev = new double[2];

for (i = 0; i < length; ++i)
{
   XX += A[i] * B[i];
   x2[0] += Math.Pow(A[i], 2.0);
   x2[1] += Math.Pow(B[i], 2.0);
   runningSum[0] += A[i];
   runningSum[1] += B[i];
}

// Compute mu
runningSum[0] = runningSum[0] / len;
runningSum[1] = runningSum[1] / len;

// Compute std deviation (bias-corrected)
stdev[0] = Math.Sqrt(x2[0] - len * Math.Pow(runningSum[0], 2)) / (len - 1);
stdev[1] = Math.Sqrt(x2[1] - len * Math.Pow(runningSum[1], 2)) / (len - 1);

// now compute correlation coefficient
correlation = (XX - (len * runningSum[0] * runningSum[1])) / (nobs - 1);
correlation = correlation / (stdev[0] * stdev[1]);

这应该会给你你正在寻找的答案。

于 2012-09-02T00:28:23.490 回答