如何从向量制作对角矩阵

How to make a diagonal matrix from a vector

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

以上代码在创建对角矩阵时导致错误/(非预期)。

如果a = [1 2 3 4]

我需要一个像这样的矩阵:

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

C = 对角线(a) 创建 C = [1]

B = 图表(a);给出错误信息:

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

我认为问题是你的 a 是矩阵。

试试这个:

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

或者,要制作一个真正的对角矩阵:

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