Main Content

trace

Sum of diagonal elements

Description

example

b = trace(A) calculates the sum of the diagonal elements of matrix A:

tr(A)=i=1naii=a11+a22+...+ann.

Examples

collapse all

Create a 3-by-3 matrix and calculate the sum of the diagonal elements.

A = [1 -5 2; 
    -3  7 9; 
     4 -1 6];

b = trace(A)
b = 14

The result tr(A)=14 agrees with a manual calculation.

A=[a11a12a13a21a22a23a31a32a33]=[1-52-3794-16],

tr(A)=i=13aii=a11+a22+a33=1+7+6=14.

Verify several properties of the trace of a matrix (up to round-off error).

Create two matrices. Verify that tr(A+B)=tr(A)+tr(B).

A = magic(3);
B = rand(3);
trace(A+B) 
ans = 17.4046
trace(A) + trace(B)
ans = 17.4046

Verify that tr(A)=tr(AT)).

trace(A)
ans = 15
trace(A')
ans = 15

Verify that tr(ATB)=tr(ABT).

trace(A'*B) 
ans = 22.1103
trace(A*B')
ans = 22.1103

Verify that tr(cA)=ctr(A) for a scalar c.

c = 5;
trace(c*A) 
ans = 75
c*trace(A)
ans = 75

Verify that the trace equals the sum of the eigenvalues tr(A)=iλi.

trace(A)
ans = 15
sum(eig(A))
ans = 15.0000

Input Arguments

collapse all

Input matrix, specified as a square matrix. A can be full or sparse.

Data Types: single | double
Complex Number Support: Yes

Algorithms

trace extracts the diagonal elements and adds them together with the command sum(diag(A)). The value of the trace is the same (up to round-off error) as the sum of the matrix eigenvalues sum(eig(A)).

Extended Capabilities

Version History

Introduced before R2006a

See Also

| |