简体   繁体   中英

Accumulating values of array elements and reiterate for entire array in MATLAB

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM