0

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.

1 Answer 1

3
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.

Sign up to request clarification or add additional context in comments.

2 Comments

Solution works perfectly well. To understand your code a little bit better, could you please tell me what part of your explantion does the [2 3 1] play?
@Joe It permutes the first (singleton) dimension to the end, which is the same as removing it. I added an explanation

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.