Search code examples
matrixoctavediagonal

Summing Diagonal Elements of Matrix in Octave


Given a square matrix M, how can you find the sum of the elements on the diagonal? There must be an easier method than this:

sum(sum(diag(diag(M), 0)))


Solution

  • Actually, what I was looking for was the trace:

    1> M = reshape(1:9, 3, 3)
    M =
    
       1   4   7
       2   5   8
       3   6   9
    
    2> trace(M)
    ans =  15