# diag

diag(M[, k])

The `k`th 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`.