Matlab中的快速滚动相关

时间:2015-02-20 09:28:56

标签: matlab correlation accumarray

我试图推导出一个计算两个向量的移动/滚动相关性的函数,速度是一个高优先级,因为我需要在数组函数中应用这个函数。我所拥有的(这太慢了)是这样的:

Data1 = rand(3000,1);
Data2 = rand(3000,1); 

function y = MovCorr(Data1,Data2)

[N,~] = size(Data1);

correlationTS = nan(N, 1);

for t = 20+1:N
    correlationTS(t, :) = corr(Data1(t-20:t, 1),Data2(t-20:t,1),'rows','complete');
end
    y = correlationTS;
end

如果我知道如何生成roling窗口索引然后应用for,我认为accumarray循环可以更有效地完成。有什么建议吗?

1 个答案:

答案 0 :(得分:2)

根据@knedlsepp的建议,并使用movingstd中的过滤器,我找到了以下解决方案,这非常快:

function Cor = MovCorr1(Data1,Data2,k)
y = zscore(Data2);
n = size(y,1);

if (n<k)
    Cor = NaN(n,1);
else
    x = zscore(Data1);
    x2 = x.^2;
    y2 = y.^2;
    xy = x .* y;
    A=1;
    B = ones(1,k);
    Stdx = sqrt((filter(B,A,x2) - (filter(B,A,x).^2)*(1/k))/(k-1));
    Stdy = sqrt((filter(B,A,y2) - (filter(B,A,y).^2)*(1/k))/(k-1));
    Cor = (filter(B,A,xy) - filter(B,A,x).*filter(B,A,y)/k)./((k-1)*Stdx.*Stdy);
    Cor(1:(k-1)) = NaN;
end
end

与原始解决方案相比,执行时间为:

tic
MovCorr(Data1,Data2);
toc
Elapsed time is 1.017552 seconds.

tic
MovCorr1(Data1,Data2,21);
toc
Elapsed time is 0.019400 seconds.