@@ -25,6 +25,7 @@ use crate::error::{self, ErrorKind, ShapeError};
25
25
use crate :: math_cell:: MathCell ;
26
26
use crate :: itertools:: zip;
27
27
use crate :: zip:: Zip ;
28
+ use crate :: AxisDescription ;
28
29
29
30
use crate :: iter:: {
30
31
AxisChunksIter , AxisChunksIterMut , AxisIter , AxisIterMut , ExactChunks , ExactChunksMut ,
@@ -511,6 +512,48 @@ where
511
512
debug_assert ! ( self . pointer_is_inbounds( ) ) ;
512
513
}
513
514
515
+ /// Slice the array in place, with a closure specifying the slice for each
516
+ /// axis.
517
+ ///
518
+ /// This is especially useful for code which is generic over the
519
+ /// dimensionality of the array.
520
+ ///
521
+ /// **Panics** if an index is out of bounds or step size is zero.
522
+ ///
523
+ /// ```
524
+ /// use ndarray::{s, Array2, ArrayBase, ArrayView, Data, Dimension, Slice};
525
+ ///
526
+ /// fn view_halved_axes<S, D>(arr: &ArrayBase<S, D>) -> ArrayView<'_, S::Elem, D>
527
+ /// where
528
+ /// S: Data,
529
+ /// D: Dimension,
530
+ /// {
531
+ ///
532
+ /// let mut view = arr.view();
533
+ /// view.slice_each_axis_inplace(|ax| Slice::from(0..ax.len() / 2));
534
+ /// view
535
+ /// }
536
+ ///
537
+ /// let a = Array2::<f32>::eye(8);
538
+ /// let v = view_halved_axes(&a);
539
+ /// assert_eq!(v, a.slice(s![..4, ..4]));
540
+ /// ```
541
+ pub fn slice_each_axis_inplace < F > ( & mut self , mut f : F )
542
+ where
543
+ F : FnMut ( AxisDescription ) -> Slice ,
544
+ {
545
+ ( 0 ..self . ndim ( ) ) . for_each ( |ax| {
546
+ self . slice_axis_inplace (
547
+ Axis ( ax) ,
548
+ f ( AxisDescription (
549
+ Axis ( ax) ,
550
+ self . dim [ ax] ,
551
+ self . strides [ ax] as isize ,
552
+ ) ) ,
553
+ )
554
+ } )
555
+ }
556
+
514
557
/// Return a reference to the element at `index`, or return `None`
515
558
/// if the index is out of bounds.
516
559
///
0 commit comments