Calculating sum of array elements and reiterate for entire array in MATLAB

别来无恙 提交于 2019-12-24 22:12:19

问题


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.

I have t=7812, p=372, w=21;

for t=1:p
   out = sum(A((t*w-w+1):(t*w)));
end

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.


回答1:


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



回答2:


Reshape into a matrix so that each block of A is a column, and compute the sum of each colum:

result = sum(reshape(A, w, []), 1);


来源:https://stackoverflow.com/questions/47135644/calculating-sum-of-array-elements-and-reiterate-for-entire-array-in-matlab

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