From 64927510e614457ff8d5150edd06432d73c87a48 Mon Sep 17 00:00:00 2001 From: Rogerluo Date: Wed, 21 Apr 2021 14:45:10 -0400 Subject: [PATCH] allow creating an undef Diagonal (#38282) --- stdlib/LinearAlgebra/src/diagonal.jl | 7 +++++++ stdlib/LinearAlgebra/test/diagonal.jl | 4 ++++ 2 files changed, 11 insertions(+) diff --git a/stdlib/LinearAlgebra/src/diagonal.jl b/stdlib/LinearAlgebra/src/diagonal.jl index e4a1899e16770..06bda6495dd0f 100644 --- a/stdlib/LinearAlgebra/src/diagonal.jl +++ b/stdlib/LinearAlgebra/src/diagonal.jl @@ -63,6 +63,13 @@ AbstractMatrix{T}(D::Diagonal) where {T} = Diagonal{T}(D) Matrix(D::Diagonal) = diagm(0 => D.diag) Array(D::Diagonal) = Matrix(D) +""" + Diagonal{T}(undef, n) + +Construct an uninitialized `Diagonal{T}` of length `n`. See `undef`. +""" +Diagonal{T}(::UndefInitializer, n::Integer) where T = Diagonal(Vector{T}(undef, n)) + # For D<:Diagonal, similar(D[, neweltype]) should yield a Diagonal matrix. # On the other hand, similar(D, [neweltype,] shape...) should yield a sparse matrix. # The first method below effects the former, and the second the latter. diff --git a/stdlib/LinearAlgebra/test/diagonal.jl b/stdlib/LinearAlgebra/test/diagonal.jl index 0ae2920fc0e86..ad2b9e8682077 100644 --- a/stdlib/LinearAlgebra/test/diagonal.jl +++ b/stdlib/LinearAlgebra/test/diagonal.jl @@ -744,6 +744,10 @@ end @test dot(zeros(Int32, 0), Diagonal(zeros(Int, 0)), zeros(Int16, 0)) === 0 end +@testset "Diagonal(undef)" begin + d = Diagonal{Float32}(undef, 2) + @test length(d.diag) == 2 +end @testset "permutedims (#39447)" begin for D in (Diagonal(zeros(5)), Diagonal(zeros(5) .+ 1im), Diagonal([[1,2],[3,4]]))