在Matlab中快速滚动相关 [英] Fast rolling correlation in Matlab

查看:342
本文介绍了在Matlab中快速滚动相关的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图派生一个用于计算两个向量的移动/滚动相关性的函数,并且速度是优先事项,因为我需要将此函数应用到数组函数中.我所拥有的(太慢了)是这样的:

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

我想如果我知道如何生成滚动窗口索引然后应用accumarray,则可以更高效地完成for循环.有什么建议吗?

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?

推荐答案

按照@knedlsepp的建议,并按照

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.

这篇关于在Matlab中快速滚动相关的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆