From 81647563b23eccce64f6b4a88dead4f93ec980d8 Mon Sep 17 00:00:00 2001 From: Martin Holters Date: Tue, 10 Nov 2020 10:19:55 +0100 Subject: [PATCH] Let `cond` of an empty square matrix return zero Fixes #778. Co-authored-by: Steven G. Johnson --- src/dense.jl | 4 ++++ test/dense.jl | 19 +++++++++++++++++++ 2 files changed, 23 insertions(+) diff --git a/src/dense.jl b/src/dense.jl index e68f7e9..24355fc 100644 --- a/src/dense.jl +++ b/src/dense.jl @@ -1779,6 +1779,10 @@ Condition number of the matrix `M`, computed using the operator `p`-norm. Valid """ function cond(A::AbstractMatrix, p::Real=2) if p == 2 + if isempty(A) + checksquare(A) + return zero(real(eigtype(eltype(A)))) + end v = svdvals(A) maxv = maximum(v) return iszero(maxv) ? oftype(real(maxv), Inf) : maxv / minimum(v) diff --git a/test/dense.jl b/test/dense.jl index 236587d..0afe9c7 100644 --- a/test/dense.jl +++ b/test/dense.jl @@ -56,6 +56,25 @@ Random.seed!(1234323) @test cond(Mars, 2) ≈ 6.181867355918493 @test cond(Mars, Inf) ≈ 7.1 end + @testset "Empty matrices" begin + # zero for square (i.e. 0×0) matrices + @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 + # error for non-square matrices + @test_throws DimensionMismatch cond(zeros(10, 0), 1) + @test_throws DimensionMismatch cond(zeros(0, 10), 1) + @test_throws DimensionMismatch cond(zeros(10, 0), 2) + @test_throws DimensionMismatch cond(zeros(0, 10), 2) + @test_throws DimensionMismatch cond(zeros(10, 0), Inf) + @test_throws DimensionMismatch cond(zeros(0, 10), Inf) + end end areal = randn(n,n)/2