MATLAB: Matlab to extract the n th diagonals in a Matrix

matrix reference

I have a matrix, for example A=[ 1 0 0 0 ; 0 2 0 0 ; 0 0 3 0 ; 0 0 0 4]; I want to reference to the n th diagonal, for example the 2nd and 4th ones, that means [2,4]. Is there a elegant way to do this without using a loop. I tried using A([2,4],[2,4]) but it gave a 2*2 matrix. Anybody knows how to do this? Thanks.

Best Answer

d = [2 4]; A(sub2ind(size(A), d, d))