Skip to content

Commit

Permalink
added extrema(A,dims)
Browse files Browse the repository at this point in the history
  • Loading branch information
bjarthur committed Mar 18, 2016
1 parent fdbcdf7 commit bc86d5e
Show file tree
Hide file tree
Showing 3 changed files with 44 additions and 2 deletions.
11 changes: 9 additions & 2 deletions base/docs/helpdb/Base.jl
Original file line number Diff line number Diff line change
Expand Up @@ -2083,11 +2083,18 @@ appended to an internal buffer of backtraces.
:@profile

"""
extrema(itr)
extrema(itr) -> Tuple
Compute both the minimum and maximum element in a single pass, and return them as a 2-tuple.
"""
extrema
extrema(itr)

"""
extrema(A,dims) -> Array{Tuple}
Compute the minimum and maximum elements of an array over the given dimensions.
"""
extrema(A,dims)

"""
isdigit(c::Union{Char,AbstractString}) -> Bool
Expand Down
32 changes: 32 additions & 0 deletions base/reduce.jl
Original file line number Diff line number Diff line change
Expand Up @@ -353,6 +353,38 @@ function extrema(itr)
return (vmin, vmax)
end

function extrema(A::AbstractArray, dims)
sz = [size(A)...]
sz[[dims...]] = 1
B = Array{Tuple{eltype(A),eltype(A)}}(sz...)
extrema_cartesian!(B, A)
end

@generated function extrema!{T,N}(B, A::Array{T,N})
quote
sA = size(A)
sB = size(B)
@nloops $N i B begin
AI = @nref $N A i
(@nref $N B i) = (AI, AI)
end
Bmax = sB
Istart = ones(Int,ndims(A))
Istart[([sB...].==1) & ([sA...].!=1)] = 2
@inbounds @nloops $N i d->(Istart[d]:size(A,d)) begin
AI = @nref $N A i
@nexprs $N d->(j_d = min(Bmax[d], i_{d}))
BJ = @nref $N B j
if AI < BJ[1]
(@nref $N B j) = (AI, BJ[2])
elseif AI > BJ[2]
(@nref $N B j) = (BJ[1], AI)
end
end
squeeze(B, tuple(find([sB...].==1)...))
end
end

## all & any

any(itr) = any(IdFun(), itr)
Expand Down
3 changes: 3 additions & 0 deletions test/reduce.jl
Original file line number Diff line number Diff line change
Expand Up @@ -167,6 +167,9 @@ prod2(itr) = invoke(prod, Tuple{Any}, itr)
@test maximum(collect(Int16(1):Int16(100))) === Int16(100)
@test maximum(Int32[1,2]) === Int32(2)

@test extrema_cartesian([1 2 3; 4 5 6; 7 8 9], 1) == [(1,7),(2,8),(3,9)]
@test extrema_cartesian([1 2 3; 4 5 6; 7 8 9], 2) == [(1,3),(4,6),(7,9)]

# any & all

@test any(Bool[]) == false
Expand Down

0 comments on commit bc86d5e

Please sign in to comment.