Vectorizing sums of different diagonals in a matrix
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