I want to vectorize the following MATLAB code. I think it must be simple but I\'m finding it confusing nevertheless.
r = some constant less than m or n
[m,n
Based on the idea of JS, and as Jonas pointed out in the comments, this can be done in two lines using IM2COL
with some array manipulation:
B = im2col(C, [r r], 'sliding');
S = reshape( sum(B(1:r+1:end,:)), size(C)-r+1 );
Basically B
contains the elements of all sliding blocks of size r-by-r over the matrix C
. Then we take the elements on the diagonal of each of these blocks B(1:r+1:end,:)
, compute their sum, and reshape the result to the expected size.
Comparing this to the convolution-based solution by Jonas, this does not perform any matrix multiplication, only indexing...