Vectorizing sums of different diagonals in a matrix

Posted by reve_etrange on Stack Overflow See other posts from Stack Overflow or by reve_etrange
Published on 2010-05-19T08:00:08Z Indexed on 2010/05/19 9:10 UTC
Read the original article Hit count: 304

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
    for j=1:n-r
        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...

© Stack Overflow or respective owner

Related posts about matlab

Related posts about vectorization