diagm
diagm(v[, k])
Construct a diagonal matrix and place v
on the k
th diagonal.
Examples

Create a diagonal matrix:
julia> v = [1, 2, 3]; julia> diagm(v) 3×3 Array{Int64,2}: 1 0 0 0 2 0 0 0 3
This example creates a diagonal matrix using the elements of vector
v
. 
Place vector on a specific diagonal:
julia> v = [4, 5]; julia> diagm(v, 1) 3×3 Array{Int64,2}: 0 4 0 0 0 5 0 0 0
The
k
argument specifies the diagonal index where the elements of vectorv
will be placed. In this example, the vectorv
is placed on the first diagonal.  Negative index for lower diagonals:
julia> v = [6, 7]; julia> diagm(v, 1) 3×3 Array{Int64,2}: 0 0 0 6 0 0 0 7 0
Using a negative value for
k
places the vectorv
on a lower diagonal.
Common mistake example:
julia> v = [1, 2, 3, 4];
julia> diagm(v, 2)
ERROR: DimensionMismatch("invalid index: 2, matrix has size (4, 4)")
In this example, the vector v
has more elements than the size of the resulting diagonal matrix. Make sure the length of the vector does not exceed the number of rows or columns in the resulting matrix.
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.