MATLAB: Average distance of nonzero diagonal to the main diagonal for sparse matrix

non zero diagonalsparse matrix

How do I find the average distance of nonzero diagonal to the main diagonal. I can get the main diagonal by diag(A), so I guess the real question is how do I get the nonzero diagonal(s) for a sparse matrix.
In the case shown in the image, the average distance of non zero diagonals is (1+3+2+3)/4 -> 2.25

Best Answer

In your example, you do not need to check the diagonals at all, just the first row and column of the matrix!
A = [0 5 0 1 0 0 ;
0 0 6 0 2 0 ;
2 0 0 4 0 3 ;
1 4 0 0 8 0 ;
0 2 5 0 0 9 ]
ix = [find(A(1,:)) find(A(:,1))']
result = mean(ix-1)
If your definition of non-zero diagonals is that at least one element of the diagonal is non-zero, this might not work. Then you should check
A = [0 0 0 1 0 0 ;
0 0 6 0 2 0 ;
0 0 0 4 0 3 ;
1 4 0 0 8 0 ;
0 2 5 0 0 9 ]
d = -size(A,1):size(A,2)
q = arrayfun(@(k) any(diag(A,k)>0), d)
d2 = d(q)
result = mean(abs(d2))