Skip to content

Commit bb138fa

Browse files
authored
Improve efficiency of minimum/maximum(::Diagonal) (#30236)
``` julia> DM = Diagonal(rand(100)); julia> @Btime minimum($DM); # before 27.987 μs (0 allocations: 0 bytes) julia> @Btime minimum($DM); # after 246.091 ns (0 allocations: 0 bytes) ```
1 parent 3b1ba62 commit bb138fa

File tree

2 files changed

+18
-0
lines changed

2 files changed

+18
-0
lines changed

stdlib/LinearAlgebra/src/diagonal.jl

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -161,6 +161,18 @@ end
161161
r
162162
end
163163

164+
function Base.minimum(D::Diagonal{T}) where T <: Number
165+
mindiag = minimum(D.diag)
166+
size(D, 1) > 1 && return (min(zero(T), mindiag))
167+
return mindiag
168+
end
169+
170+
function Base.maximum(D::Diagonal{T}) where T <: Number
171+
maxdiag = Base.maximum(D.diag)
172+
size(D, 1) > 1 && return (max(zero(T), maxdiag))
173+
return maxdiag
174+
end
175+
164176
@inline function getindex(D::Diagonal, i::Int, j::Int)
165177
@boundscheck checkbounds(D, i, j)
166178
if i == j

stdlib/LinearAlgebra/test/diagonal.jl

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -108,6 +108,12 @@ Random.seed!(1)
108108
for func in (det, tr)
109109
@test func(D) func(DM) atol=n^2*eps(relty)*(1+(elty<:Complex))
110110
end
111+
112+
if eltype(D) <: Real
113+
@test minimum(D) minimum(DM)
114+
@test maximum(D) maximum(DM)
115+
end
116+
111117
if relty <: BlasFloat
112118
for func in (exp, cis, sinh, cosh, tanh, sech, csch, coth)
113119
@test func(D) func(DM) atol=n^3*eps(relty)

0 commit comments

Comments
 (0)