Skip to content

Commit 19a09ca

Browse files
authored
Improve docs of .raw_dim(), .shape(), and .strides() (#591)
* Improve docs of .raw_dim(), .shape(), and .strides() * Add example of .shape()/.raw_dim()
1 parent 20d372a commit 19a09ca

File tree

1 file changed

+39
-3
lines changed

1 file changed

+39
-3
lines changed

src/impl_methods.rs

+39-3
Original file line numberDiff line numberDiff line change
@@ -83,17 +83,53 @@ where
8383
}
8484

8585
/// Return the shape of the array as it stored in the array.
86+
///
87+
/// This is primarily useful for passing to other `ArrayBase`
88+
/// functions, such as when creating another array of the same
89+
/// shape and dimensionality.
90+
///
91+
/// ```
92+
/// use ndarray::Array;
93+
///
94+
/// let a = Array::from_elem((2, 3), 5.);
95+
///
96+
/// // Create an array of zeros that's the same shape and dimensionality as `a`.
97+
/// let b = Array::<f64, _>::zeros(a.raw_dim());
98+
/// ```
8699
pub fn raw_dim(&self) -> D {
87100
self.dim.clone()
88101
}
89102

90103
/// Return the shape of the array as a slice.
91-
pub fn shape(&self) -> &[Ix] {
104+
///
105+
/// Note that you probably don't want to use this to create an array of the
106+
/// same shape as another array because creating an array with e.g.
107+
/// [`Array::zeros()`](ArrayBase::zeros) using a shape of type `&[usize]`
108+
/// results in a dynamic-dimensional array. If you want to create an array
109+
/// that has the same shape and dimensionality as another array, use
110+
/// [`.raw_dim()`](ArrayBase::raw_dim) instead:
111+
///
112+
/// ```rust
113+
/// use ndarray::{Array, Array2};
114+
///
115+
/// let a = Array2::<i32>::zeros((3, 4));
116+
/// let shape = a.shape();
117+
/// assert_eq!(shape, &[3, 4]);
118+
///
119+
/// // Since `a.shape()` returned `&[usize]`, we get an `ArrayD` instance:
120+
/// let b = Array::zeros(shape);
121+
/// assert_eq!(a.clone().into_dyn(), b);
122+
///
123+
/// // To get the same dimension type, use `.raw_dim()` instead:
124+
/// let c = Array::zeros(a.raw_dim());
125+
/// assert_eq!(a, c);
126+
/// ```
127+
pub fn shape(&self) -> &[usize] {
92128
self.dim.slice()
93129
}
94130

95-
/// Return the strides of the array as a slice
96-
pub fn strides(&self) -> &[Ixs] {
131+
/// Return the strides of the array as a slice.
132+
pub fn strides(&self) -> &[isize] {
97133
let s = self.strides.slice();
98134
// reinterpret unsigned integer as signed
99135
unsafe {

0 commit comments

Comments
 (0)