Search code examples
matrixjuliadiagonal

How to make a diagonal matrix from a vector


using LinearAlgebra;
        a = rand(4,1);
        B = diagm(a);
        C  = Diagonal(a);

The above code causes an error/(not intended) in creating a diagonal matrix.

if a = [1 2 3 4]

I need a matrix like:

D = [1 0 0 0;0 2 0 0;0 0 3 0;0 0 0 4].

C = Diagonal(a) creates C = [1]

B = diagm(a); gives an error message:

Error messages: ERROR: MethodError: no method matching diagm(::Matrix{Float64})

You might have used a 2d row vector where a 1d column vector was required. Note the difference between 1d column vector [1,2,3] and 2d row vector [1 2 3]. You can convert to a column vector with the vec() function. Closest candidates are: diagm(::Pair{var"#s832", var"#s831"} where {var"#s832"<:Integer, var"#s831"<:(AbstractVector{T} where T)}...) at C:\buildbot\worker\package_win64\build\usr\share\julia\stdlib\v1.6\LinearAlgebra\src\dense.jl:279 diagm(::Integer, ::Integer, ::Pair{var"#s832", var"#s831"} where {var"#s832"<:Integer, var"#s831"<:(AbstractVector{T} where T)}...) at C:\buildbot\worker\package_win64\build\usr\share\julia\stdlib\v1.6\LinearAlgebra\src\dense.jl:280 diagm(::AbstractVector{T} where T) at C:\buildbot\worker\package_win64\build\usr\share\julia\stdlib\v1.6\LinearAlgebra\src\dense.jl:329 ... Stacktrace: [1] top-level scope @ REPL[16]:1


Solution

  • I think the problem is your a is matrix.

    Try this:

    a = [1,2,3,4]  # 4-element Vector{Int64}
    C = Diagonal(a)
    4×4 Diagonal{Int64, Vector{Int64}}:
     1  ⋅  ⋅  ⋅
     ⋅  2  ⋅  ⋅
     ⋅  ⋅  3  ⋅
     ⋅  ⋅  ⋅  4
    

    Or, to make a true diagonal matrix:

    M = diagm(a)
    4×4 Matrix{Int64}:
     1  0  0  0
     0  2  0  0
     0  0  3  0
     0  0  0  4