Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add squeeze(A) method to squeeze all singleton dimensions #22000

Closed
wants to merge 1 commit into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
23 changes: 23 additions & 0 deletions base/abstractarraymath.jl
Original file line number Diff line number Diff line change
Expand Up @@ -81,6 +81,29 @@ end

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

"""
squeeze(A)

Remove all singleton dimensions from array `A`.

```jldoctest
julia> a = reshape(collect(1:4),(2,2,1,1))
2×2×1×1 Array{Int64,4}:
[:, :, 1, 1] =
1 3
2 4

julia> squeeze(a)
2×2 Array{Int64,2}:
1 3
2 4
```
"""
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Perhaps add a warning re. the potential pitfalls of this method?

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'm not sure what I would write? This function is incredibly straightforward; it removes all singleton dimensions.

Looking back over the previous discussion, it looks like the concern is that you may pass in an NxMxL matrix expecting L to equal 1, but then being surprised when M also happened to equal 1 and thus the result is a 1-dimensional array. I'm not sure how to make the docstring more explicit that such a thing will happen; that is, after all, the entire point of this function.

function squeeze(A::AbstractArray)
singleton_dims = tuple((d for d in 1:ndims(A) if size(A, d) == 1)...)
return squeeze(A, singleton_dims)
end


## Unary operators ##

Expand Down
8 changes: 8 additions & 0 deletions test/subarray.jl
Original file line number Diff line number Diff line change
Expand Up @@ -555,3 +555,11 @@ let
@test Base.IndexStyle(view(a, :, :)) == Base.IndexLinear()
@test isbits(view(a, :, :))
end

# issue
# Ensure that we can auto-squeeze out all singleton dimensions of an array
let
@test ndims(squeeze(ones(10, 1, 1))) == 1
@test ndims(squeeze(ones(1, 10))) == 1
@test ndims(squeeze(ones(10, 10))) == 2
end