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() to dynamic dimension arrays #1396

Merged
merged 1 commit into from
Aug 2, 2024
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());
barakugav marked this conversation as resolved.
Show resolved Hide resolved
/// 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();
nilgoyette marked this conversation as resolved.
Show resolved Hide resolved
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]);
}
}