Fast rolling correlation in Matlab

别来无恙 提交于 2019-12-08 10:44:46

问题


I am trying to derive a function for calculating a moving/rolling correlation for two vectors and speed is a high priority, since I need to apply this function in an array function. What I have (which is too slow) is this:

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

I am thinking that the for loop could be done more efficiently if I knew how to generate the roling window indices and then applying accumarray. Any suggestions?


回答1:


Following the advice from @knedlsepp, and using filter as in the movingstd, I found the following solution, which is quite fast:

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

Comparing with my original solution the execution times are:

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

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


来源:https://stackoverflow.com/questions/28625574/fast-rolling-correlation-in-matlab

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