2.11 Sum elements in a matrix along the diagonal

Mathematica

mat = {{1, 2, 3}, 
       {4, 5, 6}, 
       {7, 8, 9}} 
Tr[mat]
 

Out[45]= 15
 

 

Matlab

A=[1 2 3; 
   4 5 6; 
   7 8 9] 
sum(diag(A))
 

ans = 
    15
 

 

Maple

A:=Matrix([[1,2,3],[4,5,6],[7,8,9]]); 
d:=MTM:-diag(A); 
add(x,x in d);
 

Another ways

LinearAlgebra:-Diagonal(A); 
Student:-LinearAlgebra:-Diagonal(A);
 

15