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] = size(C);
S = zeros(m-r,n-r);
for i=1:m-r+1
for j=1:n-r+1
S(i,j) = sum(diag(C(i:i+r-1,j:j+r-1)));
end
end
The code calculates a table of scores, S, for a dynamic programming algorithm, from another score table, C.
The diagonal summing is to generate scores for individual pieces of the data used to generate C, for all possible pieces (of size r).
Thanks in advance for any answers! Sorry if this one should be obvious...
Note
The built-in conv2 turned out to be faster than convnfft, because my eye(r) is quite small ( 5 <= r <= 20 ). convnfft.m states that r should be > 20 for any benefit to manifest.
So only include the sum of all of the elements on the primary diagonal and all the elements on the secondary diagonal and ignore the crossing element. then the output will be The primary diagonal elements are [10,15,12,3] sum is 40, secondary diagonal [6,3,8,2] sum is 19, so total sum 59.
Sometimes we need to find the sum of the Upper right, Upper left, Lower right, or lower left diagonal elements. Numpy provides us the facility to compute the sum of different diagonals elements using numpy. trace() and numpy. diagonal() method.
Efficient approach: The idea to find the sum of values of principal diagonal is to iterate to N and use the value of matrix[row][row] for the summation of principle diagonal and to find the sum of values of secondary diagonal is to use the value of matrix[row][N – (row + 1)] for summation.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With