gpt4 book ai didi

matrix - 如何从向量制作对角矩阵

转载 作者:行者123 更新时间:2023-12-04 12:30:15 24 4
gpt4 key购买 nike

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 = Diagonal(a) 创建
C = [1]
B = 图示(a);给出错误信息:

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

You might have used a 2d row vector where a 1d column vector wasrequired. Note the difference between 1d column vector [1,2,3] and 2drow 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)}...) atC:\buildbot\worker\package_win64\build\usr\share\julia\stdlib\v1.6\LinearAlgebra\src\dense.jl:279diagm(::Integer, ::Integer, ::Pair{var"#s832", var"#s831"} where{var"#s832"<:Integer, var"#s831"<:(AbstractVector{T} where T)}...) atC:\buildbot\worker\package_win64\build\usr\share\julia\stdlib\v1.6\LinearAlgebra\src\dense.jl:280diagm(::AbstractVector{T} where T) atC:\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

关于matrix - 如何从向量制作对角矩阵,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69609872/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com