diff --git a/stdlib/LinearAlgebra/src/dense.jl b/stdlib/LinearAlgebra/src/dense.jl index f6c8c34e5531a..d4907ac2f1802 100644 --- a/stdlib/LinearAlgebra/src/dense.jl +++ b/stdlib/LinearAlgebra/src/dense.jl @@ -1456,6 +1456,7 @@ Condition number of the matrix `M`, computed using the operator `p`-norm. Valid """ function cond(A::AbstractMatrix, p::Real=2) if p == 2 + isempty(A) && return zero(real(eigtype(eltype(A)))) v = svdvals(A) maxv = maximum(v) return iszero(maxv) ? oftype(real(maxv), Inf) : maxv / minimum(v) diff --git a/stdlib/LinearAlgebra/test/dense.jl b/stdlib/LinearAlgebra/test/dense.jl index 8ab539e8e3d59..a0c69eaf51900 100644 --- a/stdlib/LinearAlgebra/test/dense.jl +++ b/stdlib/LinearAlgebra/test/dense.jl @@ -39,6 +39,19 @@ Random.seed!(1234321) M = [1.0 -2.0; -2.0 -1.5] @test cond(M, 1) ≈ 2.227272727272727 end + @testset "Empty matrices" begin + @test cond(zeros(Int, 0, 0), 1) === 0.0 + @test cond(zeros(Int, 0, 0), 2) === 0.0 + @test cond(zeros(Int, 0, 0), Inf) === 0.0 + @test cond(zeros(0, 0), 1) === 0.0 + @test cond(zeros(0, 0), 2) === 0.0 + @test cond(zeros(0, 0), Inf) === 0.0 + @test cond(zeros(ComplexF64, 0, 0), 1) === 0.0 + @test cond(zeros(ComplexF64, 0, 0), 2) === 0.0 + @test cond(zeros(ComplexF64, 0, 0), Inf) === 0.0 + @test cond(zeros(10, 0)) === 0.0 + @test cond(zeros(0, 10)) === 0.0 + end end areal = randn(n,n)/2