Vectorizing sums of different diagonals in a matrix

后端 未结 4 1831
慢半拍i
慢半拍i 2021-01-17 17:46

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         


        
4条回答
  •  清酒与你
    2021-01-17 18:13

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

提交回复
热议问题