trace
trace(M)
Matrix trace
Examples
The trace
function in Julia calculates the sum of diagonal elements of a matrix.
julia> A = [1 2 3; 4 5 6; 7 8 9]
3×3 Array{Int64,2}:
1 2 3
4 5 6
7 8 9
julia> trace(A)
15
Here are some common examples of how to use the trace
function:

Calculate trace of a square matrix:
julia> M = [1 2 3; 4 5 6; 7 8 9]; julia> trace(M) 15
This calculates the trace of the matrix
M
which is the sum of the diagonal elements (1 + 5 + 9).  Calculate trace of a larger matrix:
julia> M = [1 2 3 4; 5 6 7 8; 9 10 11 12; 13 14 15 16]; julia> trace(M) 34
It works with matrices of any size as long as they are square.
Common mistake example:
julia> M = [1 2; 3 4; 5 6];
julia> trace(M)
ERROR: MethodError: no method matching trace(::Array{Int64,2})
In this example, the input matrix M
is not a square matrix. The trace
function can only be applied to square matrices. Ensure that the input matrix is square to avoid such errors.
See Also
Ac_ldiv_B, Ac_ldiv_Bc, Ac_mul_B, Ac_mul_Bc, Ac_rdiv_B, Ac_rdiv_Bc, At_ldiv_B, At_ldiv_Bt, At_mul_B, At_mul_Bt, At_rdiv_B, At_rdiv_Bt, A_ldiv_Bc, A_ldiv_Bt, A_mul_B!, A_mul_Bc, A_mul_Bt, A_rdiv_Bc, A_rdiv_Bt, Bidiagonal, cond, conv2, det, diag, diagind, diagm, diff, eig, eigvals, eigvecs, expm, eye, full, inv, isdiag, ishermitian, isposdef, isposdef!, issym, istril, istriu, logabsdet, logdet, lyap, norm, qrfact, rank, repmat, rot180, rotl90, rotr90, sortrows, sqrtm, SymTridiagonal, trace, Tridiagonal, tril, tril!, triu, triu!, writedlm,User Contributed Notes
Add a Note
The format of note supported is markdown, use triple backtick to start and end a code block.