3

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)))

Chris Tang
  • 567
  • 7
  • 18
grifaton
  • 3,986
  • 4
  • 30
  • 42

2 Answers2

8

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
grifaton
  • 3,986
  • 4
  • 30
  • 42
7

Just sum(diag(M)) seems to work fine.

1> M = reshape(1:9, 3, 3)
M =

   1   4   7
   2   5   8
   3   6   9

2> sum(diag(M))
ans =  15
Fred Foo
  • 355,277
  • 75
  • 744
  • 836