Skip to content
Merged
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
56 changes: 56 additions & 0 deletions src/impl_dyn.rs
Original file line number Diff line number Diff line change
Expand Up @@ -58,4 +58,60 @@ where S: Data<Elem = A>
self.dim = self.dim.remove_axis(axis);
self.strides = self.strides.remove_axis(axis);
}

/// Remove axes of length 1 and return the modified array.
///
/// If the array has more the one dimension, the result array will always
/// have at least one dimension, even if it has a length of 1.
///
/// ```
/// use ndarray::{arr1, arr2, arr3};
///
/// let a = arr3(&[[[1, 2, 3]], [[4, 5, 6]]]).into_dyn();
/// assert_eq!(a.shape(), &[2, 1, 3]);
/// let b = a.squeeze();
/// assert_eq!(b, arr2(&[[1, 2, 3], [4, 5, 6]]).into_dyn());
/// assert_eq!(b.shape(), &[2, 3]);
///
/// let c = arr2(&[[1]]).into_dyn();
/// assert_eq!(c.shape(), &[1, 1]);
/// let d = c.squeeze();
/// assert_eq!(d, arr1(&[1]).into_dyn());
/// assert_eq!(d.shape(), &[1]);
/// ```
#[track_caller]
pub fn squeeze(self) -> Self
{
let mut out = self;
for axis in (0..out.shape().len()).rev() {
if out.shape()[axis] == 1 && out.shape().len() > 1 {
out = out.remove_axis(Axis(axis));
}
}
out
}
}

#[cfg(test)]
mod tests
{
use crate::{arr1, arr2, arr3};

#[test]
fn test_squeeze()
{
let a = arr3(&[[[1, 2, 3]], [[4, 5, 6]]]).into_dyn();
assert_eq!(a.shape(), &[2, 1, 3]);

let b = a.squeeze();
assert_eq!(b, arr2(&[[1, 2, 3], [4, 5, 6]]).into_dyn());
assert_eq!(b.shape(), &[2, 3]);

let c = arr2(&[[1]]).into_dyn();
assert_eq!(c.shape(), &[1, 1]);

let d = c.squeeze();
assert_eq!(d, arr1(&[1]).into_dyn());
assert_eq!(d.shape(), &[1]);
}
}