MATLAB: How to Sum matrix diagonals

matrixmatrix manipulation

If I have the following matrix
a = [1 2 3; 4 5 6; 7 8 10
a =
1 2 3
4 5 6
7 8 10
How do I sum the diagonal of 7,5,3? I know that to sum 1,5,10 I use
sum(diag(a))
But when I try
sum(diag(a,2))
The answer is 3. Is there a built in function that calculates the sum, or do I have to make a while loop?

Best Answer

sum(diag(a(:,end:-1:1)));
or summing all diagonals:
sum(spdiags(rot90(a)));
Related Question