@@ -4,7 +4,7 @@ module HigherOrderFns
4
4
5
5
# This module provides higher order functions specialized for sparse arrays,
6
6
# particularly map[!]/broadcast[!] for SparseVectors and SparseMatrixCSCs at present.
7
- import Base: map, map!, broadcast, copy, copyto!
7
+ import Base: map, map!, broadcast, copy, copyto!, extrema
8
8
9
9
using Base: front, tail, to_shape
10
10
using .. SparseArrays: SparseVector, SparseMatrixCSC, AbstractSparseVector, AbstractSparseMatrixCSC,
@@ -29,6 +29,7 @@ using LinearAlgebra
29
29
# (11) Define broadcast[!] methods handling combinations of scalars, sparse vectors/matrices,
30
30
# structured matrices, and one- and two-dimensional Arrays.
31
31
# (12) Define map[!] methods handling combinations of sparse and structured matrices.
32
+ # (13) Define extrema methods optimized for sparse vectors/matrices.
32
33
33
34
34
35
# (0) BroadcastStyle rules and convenience types for dispatch
@@ -1154,4 +1155,23 @@ map(f::Tf, A::SparseOrStructuredMatrix, Bs::Vararg{SparseOrStructuredMatrix,N})
1154
1155
map! (f:: Tf , C:: AbstractSparseMatrixCSC , A:: SparseOrStructuredMatrix , Bs:: Vararg{SparseOrStructuredMatrix,N} ) where {Tf,N} =
1155
1156
(_checksameshape (C, A, Bs... ); _noshapecheck_map! (f, C, _sparsifystructured (A), map (_sparsifystructured, Bs)... ))
1156
1157
1158
+
1159
+ # (13) extrema methods optimized for sparse vectors/matrices.
1160
+ function extrema (f, A:: SparseVecOrMat )
1161
+ if iszero (length (A))
1162
+ throw (ArgumentError (" Sparse array must have at least one element." ))
1163
+ end
1164
+ N = nnz (A)
1165
+ iszero (N) && return f (zero (eltype (A))), f (zero (eltype (A)))
1166
+ vmin, vmax = extrema (f, nonzeros (A))
1167
+ if N != length (A)
1168
+ f0 = f (zero (eltype (A)))
1169
+ vmin = min (f0, vmin)
1170
+ vmax = max (f0, vmax)
1171
+ end
1172
+ vmin, vmax
1173
+ end
1174
+
1175
+ extrema (A:: SparseVecOrMat ) = extrema (identity, A)
1176
+
1157
1177
end
0 commit comments