滑动Window:高效计算累积最大值
Sliding Window: Efficiently Calculating the Cumulative Maximum
我有一个二维矩阵 A
,其中每一列代表一个时间序列。
对于每个时间序列,我需要计算每个 window 长度的累积最大值 k
:
RESULT = nan(size(A));
% loop over each time-series.
for col = 1:size(A, 2)
% loop over the elements of the time-series (excluding the first 'k-1' elements).
for row = k:size(A, 1)
% extract the sliding window.
window = A((row-k+1):row, col);
% calculate the cumulative maximum of that sliding window.
cumax_vector = cummax(window);
% do something with it.
RESULT(row,col) = ...;
end
end
我意识到为 A
的每个元素提取滑动 window
然后计算包含其累积最大值的向量是非常低效的。
有没有办法更有效地做到这一点?
您可以重新排列矩阵 A 并在新矩阵上计算 cummax,
为此,您应该首先创建一个索引矩阵 (C),然后计算 cummax(A(C))
我用下面的例子演示了这个方法,为了简单起见,我假设A是5x1矩阵,k=3
对于 2d A 矩阵,您可以在 A 的列上循环,或者您可以简单地创建一个 3d 索引矩阵广告等等。
>> A=rand(5,1)
A =
0.6557
0.0357
0.8491
0.9340
0.6787
>> C=ones(3,3).*(1:3)'+(0:1:2)
C =
1 2 3
2 3 4
3 4 5
>> A(C)
ans =
0.6557 0.0357 0.8491
0.0357 0.8491 0.9340
0.8491 0.9340 0.6787
>> cummax(A(C))
ans =
0.6557 0.0357 0.8491
0.6557 0.8491 0.9340
0.8491 0.9340 0.9340
编辑 1:
如果您没有足够的内存来一次计算整个 A,您可以计算索引矩阵并将其切片,然后在每个切片上计算 cummax。在一个循环中。每次迭代后,您应该将结果写入文件并清除变量以释放内存。
我有一个二维矩阵 A
,其中每一列代表一个时间序列。
对于每个时间序列,我需要计算每个 window 长度的累积最大值 k
:
RESULT = nan(size(A));
% loop over each time-series.
for col = 1:size(A, 2)
% loop over the elements of the time-series (excluding the first 'k-1' elements).
for row = k:size(A, 1)
% extract the sliding window.
window = A((row-k+1):row, col);
% calculate the cumulative maximum of that sliding window.
cumax_vector = cummax(window);
% do something with it.
RESULT(row,col) = ...;
end
end
我意识到为 A
的每个元素提取滑动 window
然后计算包含其累积最大值的向量是非常低效的。
有没有办法更有效地做到这一点?
您可以重新排列矩阵 A 并在新矩阵上计算 cummax, 为此,您应该首先创建一个索引矩阵 (C),然后计算 cummax(A(C))
我用下面的例子演示了这个方法,为了简单起见,我假设A是5x1矩阵,k=3 对于 2d A 矩阵,您可以在 A 的列上循环,或者您可以简单地创建一个 3d 索引矩阵广告等等。
>> A=rand(5,1)
A =
0.6557
0.0357
0.8491
0.9340
0.6787
>> C=ones(3,3).*(1:3)'+(0:1:2)
C =
1 2 3
2 3 4
3 4 5
>> A(C)
ans =
0.6557 0.0357 0.8491
0.0357 0.8491 0.9340
0.8491 0.9340 0.6787
>> cummax(A(C))
ans =
0.6557 0.0357 0.8491
0.6557 0.8491 0.9340
0.8491 0.9340 0.9340
编辑 1: 如果您没有足够的内存来一次计算整个 A,您可以计算索引矩阵并将其切片,然后在每个切片上计算 cummax。在一个循环中。每次迭代后,您应该将结果写入文件并清除变量以释放内存。