计算数组元素的总和并在MATLAB中为整个数组重复 [英] Calculating sum of array elements and reiterate for entire array in MATLAB
问题描述
我有一个大小为7812x1的向量A
,想计算长度为21的固定窗口的总和(因此为372个块).应该重申这一点,以便输出应返回大小为372x1的向量.
I have a vector A
of size 7812x1 and would like to calculate the sum of fixed windows of length 21 (so 372 blocks). This should be reiterated, so that the output should return a vector of size 372x1.
我有t=7812
,p=372
,w=21
;
for t=1:p
out = sum(A((t*w-w+1):(t*w)));
end
但是,此代码不起作用.我的想法是,零件((t*w-w+1):(t*w))
允许滚动窗口之类的东西.该窗口的长度为21,因此实际上不需要使用变量来表达它,但我认为它具有一定的灵活性.
This code, however, does not work. My idea is that the part ((t*w-w+1):(t*w))
allows for something like a rolling window. The window is of length 21, so there is not really a need to express is with variables, yet I think it keeps some flexibility.
我已经看到了潜在的相关问题(例如向量的部分和),但是我不确定这是否会导致所需的输出.
I've seen potentially related questions (such a partial sum of a vector), yet I'm not sure whether this would result the output desired.
推荐答案
遵循使用滚动/移动窗口的想法(需要Matlab 2016a或更高版本):
Following your idea of using a rolling/moving window (requires Matlab 2016a or later):
t = 7812; w = 21; % your parameters
A = rand(t,1); % generate some test data
B = movsum(A,w); % the sum of a moving window with width w
out = B(ceil(w/2):w:end); % get every w'th element
这篇关于计算数组元素的总和并在MATLAB中为整个数组重复的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!