在朱莉娅中使用理解创建矩阵
Create matrix using comprehension in julia
我想创建一个对角线是 1/2 的幂的对角矩阵。我知道我可以做到:
A = Diagonal(1, 1/2, 1/2^2, ..., 1/2^10)
我想知道是否有一种方法可以使用理解来做到这一点,就像这样:
A = Diagonal((1/2)^x for x=[0:10])
Diagonal
constructor takes the diagonal as a vector for input, so just use a regular vector comprehension:
julia> using LinearAlgebra
julia> Diagonal([1/2^i for i in 0:4])
5×5 Diagonal{Float64, Vector{Float64}}:
1.0 ⋅ ⋅ ⋅ ⋅
⋅ 0.5 ⋅ ⋅ ⋅
⋅ ⋅ 0.25 ⋅ ⋅
⋅ ⋅ ⋅ 0.125 ⋅
⋅ ⋅ ⋅ ⋅ 0.0625
我想创建一个对角线是 1/2 的幂的对角矩阵。我知道我可以做到:
A = Diagonal(1, 1/2, 1/2^2, ..., 1/2^10)
我想知道是否有一种方法可以使用理解来做到这一点,就像这样:
A = Diagonal((1/2)^x for x=[0:10])
Diagonal
constructor takes the diagonal as a vector for input, so just use a regular vector comprehension:
julia> using LinearAlgebra
julia> Diagonal([1/2^i for i in 0:4])
5×5 Diagonal{Float64, Vector{Float64}}:
1.0 ⋅ ⋅ ⋅ ⋅
⋅ 0.5 ⋅ ⋅ ⋅
⋅ ⋅ 0.25 ⋅ ⋅
⋅ ⋅ ⋅ 0.125 ⋅
⋅ ⋅ ⋅ ⋅ 0.0625