Reputation: 312
I want to create a diagonal matrix whose diagonals are powers of 1/2. I know I could do:
A = Diagonal(1, 1/2, 1/2^2, ..., 1/2^10)
I was wondering if there is a way to do this using a comprehension, something like this:
A = Diagonal((1/2)^x for x=[0:10])
Upvotes: 2
Views: 507
Reputation: 10984
The 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
Upvotes: 4