MATLAB: Accessing all elements along the diagonals and rows (simple backprojection algorithm for image reconstruction)

back projection algorithmdiagonalimage reconstruction

Hi, I'm wondering how to effectively sum all elements along every diagonal and row that touches an element in a given matrix. For example, in the matrix below
1 2 3
4 5 6
7 8 9
I would like to compute 1 + (1+2+3)/3 + (1+5+9)/3 + (1+4+7)/3. This value should replace the element 1 at (1,1). To replace the element 2 at (1,2), it would be (2+4)/2 + (2+6)/2 + (1+2+3)/3 + (2+5+8)/3. Similarly, element 6 at (2,3) should be (2+6)/2 + (6+8)/2 + (4+5+6)/3 + (3+6+9)/3.
It's a bit like a Sudoku calculation. The algorithm needs to be flexible for any square matrix, of any size (my data set is 360×360). Any help is much appreciated!

Best Answer

You can indeed use convolutions:
m = reshape(1:100, 10, 10); %demo matrix
convlength = 2 * size(m, 1); %also 2 * size(m, 2) since m is square
%size of convolution matrices is twice the size of the input matrix to make sure every element is always taken into account
rowmean = conv2(m, ones(1, convlength) / convlength * 2, 'same');
colmean = conv2(m, ones(convlength, 1) / convlength * 2, 'same');
diagsum = conv2(m, eye(convlength), 'same');
diagcount = toeplitz(size(m, 1):-1:1);
diagmean = diagsum ./ diagcount;
antidiagsum = conv2(fliplr(m), eye(convlength), 'same');
antidiagmean = fliplr(antidiagsum ./ diagcount);
result = rowmean + colmean + diagmean + antidiagmean