ndarray/
impl_dyn.rs

1// Copyright 2018 bluss and ndarray developers.
2//
3// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
4// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
5// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
6// option. This file may not be copied, modified, or distributed
7// except according to those terms.
8
9//! Methods for dynamic-dimensional arrays.
10use crate::imp_prelude::*;
11
12/// # Methods for Dynamic-Dimensional Arrays
13impl<A, S> ArrayBase<S, IxDyn>
14where
15    S: Data<Elem = A>,
16{
17    /// Insert new array axis of length 1 at `axis`, modifying the shape and
18    /// strides in-place.
19    ///
20    /// **Panics** if the axis is out of bounds.
21    ///
22    /// ```
23    /// use ndarray::{Axis, arr2, arr3};
24    ///
25    /// let mut a = arr2(&[[1, 2, 3], [4, 5, 6]]).into_dyn();
26    /// assert_eq!(a.shape(), &[2, 3]);
27    ///
28    /// a.insert_axis_inplace(Axis(1));
29    /// assert_eq!(a, arr3(&[[[1, 2, 3]], [[4, 5, 6]]]).into_dyn());
30    /// assert_eq!(a.shape(), &[2, 1, 3]);
31    /// ```
32    pub fn insert_axis_inplace(&mut self, axis: Axis) {
33        assert!(axis.index() <= self.ndim());
34        self.dim = self.dim.insert_axis(axis);
35        self.strides = self.strides.insert_axis(axis);
36    }
37
38    /// Collapses the array to `index` along the axis and removes the axis,
39    /// modifying the shape and strides in-place.
40    ///
41    /// **Panics** if `axis` or `index` is out of bounds.
42    ///
43    /// ```
44    /// use ndarray::{Axis, arr1, arr2};
45    ///
46    /// let mut a = arr2(&[[1, 2, 3], [4, 5, 6]]).into_dyn();
47    /// assert_eq!(a.shape(), &[2, 3]);
48    ///
49    /// a.index_axis_inplace(Axis(1), 1);
50    /// assert_eq!(a, arr1(&[2, 5]).into_dyn());
51    /// assert_eq!(a.shape(), &[2]);
52    /// ```
53    pub fn index_axis_inplace(&mut self, axis: Axis, index: usize) {
54        self.collapse_axis(axis, index);
55        self.dim = self.dim.remove_axis(axis);
56        self.strides = self.strides.remove_axis(axis);
57    }
58}