diag

diag(M[, k])

The kth diagonal of a matrix, as a vector. Use diagm to construct a diagonal matrix.

Examples

In the Julia programming language, the function diag(M[, k]) is used to extract the k-th diagonal of a matrix M as a vector.

julia> M = [1 2 3; 4 5 6; 7 8 9]
3×3 Array{Int64,2}:
 1  2  3
 4  5  6
 7  8  9

julia> diag(M, 1)
2-element Array{Int64,1}:
 2
 6

This example extracts the first superdiagonal of the matrix M as a vector.

julia> M = [1 2 3; 4 5 6; 7 8 9]
3×3 Array{Int64,2}:
 1  2  3
 4  5  6
 7  8  9

julia> diag(M, -1)
2-element Array{Int64,1}:
 4
 8

This example extracts the first subdiagonal of the matrix M as a vector.

julia> M = [1 2 3; 4 5 6; 7 8 9]
3×3 Array{Int64,2}:
 1  2  3
 4  5  6
 7  8  9

julia> diag(M)
3-element Array{Int64,1}:
 1
 5
 9

This example extracts the main diagonal of the matrix M as a vector.

julia> M = [1 2 3; 4 5 6; 7 8 9]
3×3 Array{Int64,2}:
 1  2  3
 4  5  6
 7  8  9

julia> diag(M, 2)
0-element Array{Int64,1}

This example extracts the second superdiagonal of the matrix M as a vector. In this case, the resulting vector is empty as there are no elements in the specified diagonal.

Common mistake example:

julia> M = [1 2 3; 4 5 6; 7 8 9]
3×3 Array{Int64,2}:
 1  2  3
 4  5  6
 7  8  9

julia> diag(M, 4)
ERROR: ArgumentError: invalid diagonal index: 4, valid range is -2:2

In this example, the k value provided is out of the valid range for the matrix M. It's important to ensure that the k value is within the valid range to avoid such errors. Always check that the k value is within the appropriate range before using diag.

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.

*Required Field
Details

Checking you are not a robot: