Skip to content

Commit

Permalink
Add squeeze(f, A, dims) for reductions to drop dims
Browse files Browse the repository at this point in the history
This simple definition makes it easier to write reductions that drops the dimensions over which they reduce. Fixes #16606, addresses part of the root issue in #22000.
  • Loading branch information
mbauman committed Aug 29, 2017
1 parent 9089b13 commit fc2eeee
Show file tree
Hide file tree
Showing 2 changed files with 17 additions and 0 deletions.
6 changes: 6 additions & 0 deletions base/abstractarraymath.jl
Original file line number Diff line number Diff line change
Expand Up @@ -83,6 +83,12 @@ end

squeeze(A::AbstractArray, dim::Integer) = squeeze(A, (Int(dim),))

"""
squeeze(f, A, dims)
Compute reduction `f` over dimensions `dims` in array `A` and drop those dimensions from the result.
"""
squeeze(f, A::AbstractArray, dims::Union{Dims, Integer}) = squeeze(f(A, dims), dims)

## Unary operators ##

Expand Down
11 changes: 11 additions & 0 deletions test/arrayops.jl
Original file line number Diff line number Diff line change
Expand Up @@ -219,6 +219,17 @@ end
@test_throws ArgumentError squeeze(a, 4)
@test_throws ArgumentError squeeze(a, 6)

@test @inferred(squeeze(sum, a, 1)) == @inferred(squeeze(sum, a, (1,))) == reshape(sum(a, 1), (1, 8, 8, 1))
@test @inferred(squeeze(sum, a, 3)) == @inferred(squeeze(sum, a, (3,))) == reshape(sum(a, 3), (1, 1, 8, 1))
@test @inferred(squeeze(sum, a, 4)) == @inferred(squeeze(sum, a, (4,))) == reshape(sum(a, 4), (1, 1, 8, 1))
@test @inferred(squeeze(sum, a, (1, 5))) == squeeze(sum, a, (5, 1)) == reshape(sum(a, (5, 1)), (1, 8, 8))
@test @inferred(squeeze(sum, a, (1, 2, 5))) == squeeze(sum, a, (5, 2, 1)) == reshape(sum(a, (5, 2, 1)), (8, 8))
@test_throws ArgumentError squeeze(sum, a, 0)
@test_throws ArgumentError squeeze(sum, a, (1, 1))
@test_throws ArgumentError squeeze(sum, a, (1, 2, 1))
@test_throws ArgumentError squeeze(sum, a, (1, 1, 2))
@test_throws ArgumentError squeeze(sum, a, 6)

sz = (5,8,7)
A = reshape(1:prod(sz),sz...)
@test A[2:6] == [2:6;]
Expand Down

0 comments on commit fc2eeee

Please sign in to comment.