Vectorizing sums of different diagonals in a matrix

后端 未结 4 1872
慢半拍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条回答
  •  旧时难觅i
    2021-01-17 18:02

    If I understand correctly, you're trying to calculate the diagonal sum of every subarray of C, where you have removed the last row and column of C (if you should not remove the row/col, you need to loop to m-r+1, and you need to pass the entire array C to the function in my solution below).

    You can do this operation via a convolution, like so:

    S = conv2(C(1:end-1,1:end-1),eye(r),'valid');
    

    If C and r are large, you may want to have a look at CONVNFFT from the Matlab File Exchange to speed up calculations.

提交回复
热议问题