2D moving sum of a matrix

29 views (last 30 days)
Hi there
How do I perform a moving sum within a matrix? I.e.: the result of each index will be the sum of all surrounding indexes, as defined by window lengths (with some edge effects, as with a regular moving sum).
I could definitely set up some basic loop function but I anticipate having to do this quite often and so I wish to find a smarter/faster solution. And I suspect that there definitely is a smarter solution. Like maybe using filter2 or something?
Thanks in advance for all help!
  1 Comment
KSSV on 16 Aug 2020
There is inbuilt function movsum, did you see that?

Sign in to comment.

Accepted Answer

Bruno Luong
Bruno Luong on 16 Aug 2020
Edited: Bruno Luong on 16 Aug 2020
Assuming A is your array, w is the window size
% testexample
% or
conv2(A, ones(w), 'same')
% or
filter2(ones(w), A, 'same')
  1 Comment
Jakob Sievers
Jakob Sievers on 16 Aug 2020
Thank you so much for this. I knew there was a simple way to do this.
I ended up using fspecial to create a circular sum-filter instead of a basic square sum-filter:

Sign in to comment.

More Answers (1)

Walter Roberson
Walter Roberson on 16 Aug 2020
conv2(YourMatrix, ones(WindowHeight, WindowWidth))
You might want to add options such as 'valid' to control the size of output and the edge effects.




Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!