是否存在与Matlab的二维相关系数等效的函数?我想在2个1-d阵列上使用它。 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))
由于
答案 0 :(得分:0)
假设您的所有数据已加载到两个数组A and B
中,您要执行的操作如下。此外,假设您的两个数组长度相等且没有NaN和无穷大值。
此外,由于您只有两个数据点,因此您的相关矩阵只包含一个非对角线值,因此我将其存储为单个双值。
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]);
这应该可以为您提供所需的答案。