Reputation: 453
I have a matrix A
of size 3780x30974. This matrix consists of 0
and 1
. I would like to calculate the sum of fixed windows of length 21
(180 blocks). This should be reiterated, so that the output returns a vector of size 180x30974.
If the first 21 values in a column have a value of 1, the output should return 21. However, if the following 21 values have a value of 1 again, it should return 21 as well. In my code, it accumulates the values, so I obtain 42.
I have t=3780
, p=180
, w=21
;
B = movsum(A,w); % the sum of a moving window with width w
This question is somehow related to a question previously asked, yet with a different problem setting. I thought about a loop to say "perform from t=1:p
", yet it didn't work.
Upvotes: 0
Views: 89
Reputation: 112679
result = permute(sum(reshape(A, w, [], size(A,2)), 1), [2 3 1]);
This works as follows: reshape A
into a 3D array of size 21
×180
×30974
:
reshape(A, w, [], size(A,2)), 1)
then sum along the first dimension
sum(..., 1)
and finally remove the first (singleton) dimension by permuting it to the end:
permute(..., [2 3 1])
Note that Matlab arrays have an infinite number of trailing singleton dimensions, so moving a singleton dimension to the end is the same as removing it.
Upvotes: 3