Type Alias ndarray::Array

source ·
pub type Array<A, D> = ArrayBase<OwnedRepr<A>, D>;
Expand description

An array that owns its data uniquely.

Array is the main n-dimensional array type, and it owns all its array elements.

The Array<A, D> is parameterized by A for the element type and D for the dimensionality.

ArrayBase is used to implement both the owned arrays and the views; see its docs for an overview of all array features.

See also:

Aliased Type§

struct Array<A, D> { /* private fields */ }

Implementations§

source§

impl<A> Array<A, Ix0>

Methods specific to Array0.

See also all methods for ArrayBase

source

pub fn into_scalar(self) -> A

Returns the single element in the array without cloning it.

use ndarray::{arr0, Array0};

// `Foo` doesn't implement `Clone`.
#[derive(Debug, Eq, PartialEq)]
struct Foo;

let array: Array0<Foo> = arr0(Foo);
let scalar: Foo = array.into_scalar();
assert_eq!(scalar, Foo);
source§

impl<A, D> Array<A, D>
where D: Dimension,

Methods specific to Array.

See also all methods for ArrayBase

source

pub fn into_raw_vec_and_offset(self) -> (Vec<A>, Option<usize>)

Return a vector of the elements in the array, in the way they are stored internally, and the index in the vector corresponding to the logically first element of the array (or 0 if the array is empty).

If the array is in standard memory layout, the logical element order of the array (.iter() order) and of the returned vector will be the same.

use ndarray::{array, Array2, Axis};

let mut arr: Array2<f64> = array![[1., 2.], [3., 4.], [5., 6.]];
arr.slice_axis_inplace(Axis(0), (1..).into());
assert_eq!(arr[[0, 0]], 3.);
let copy = arr.clone();

let shape = arr.shape().to_owned();
let strides = arr.strides().to_owned();
let (v, offset) = arr.into_raw_vec_and_offset();

assert_eq!(v, &[1., 2., 3., 4., 5., 6.]);
assert_eq!(offset, Some(2));
assert_eq!(v[offset.unwrap()], 3.);
for row in 0..shape[0] {
    for col in 0..shape[1] {
        let index = (
            offset.unwrap() as isize
            + row as isize * strides[0]
            + col as isize * strides[1]
        ) as usize;
        assert_eq!(v[index], copy[[row, col]]);
    }
}

In the case of zero-sized elements, the offset to the logically first element is somewhat meaningless. For convenience, an offset will be returned such that all indices computed using the offset, shape, and strides will be in-bounds for the Vec<A>. Note that this offset won’t necessarily be the same as the offset for an array of nonzero-sized elements sliced in the same way.

use ndarray::{array, Array2, Axis};

let mut arr: Array2<()> = array![[(), ()], [(), ()], [(), ()]];
arr.slice_axis_inplace(Axis(0), (1..).into());

let shape = arr.shape().to_owned();
let strides = arr.strides().to_owned();
let (v, offset) = arr.into_raw_vec_and_offset();

assert_eq!(v, &[(), (), (), (), (), ()]);
for row in 0..shape[0] {
    for col in 0..shape[1] {
        let index = (
            offset.unwrap() as isize
            + row as isize * strides[0]
            + col as isize * strides[1]
        ) as usize;
        assert_eq!(v[index], ());
    }
}
source

pub fn into_raw_vec(self) -> Vec<A>

👎Deprecated since 0.16.0: Use .into_raw_vec_and_offset() instead

Return a vector of the elements in the array, in the way they are stored internally.

Depending on slicing and strides, the logically first element of the array can be located at an offset. Because of this, prefer to use .into_raw_vec_and_offset() instead.

source§

impl<A> Array<A, Ix2>

Methods specific to Array2.

See also all methods for ArrayBase

source

pub fn push_row(&mut self, row: ArrayView<'_, A, Ix1>) -> Result<(), ShapeError>
where A: Clone,

Append a row to an array

The elements from row are cloned and added as a new row in the array.

Errors with a shape error if the length of the row does not match the length of the rows in the array.

The memory layout of the self array matters for ensuring that the append is efficient. Appending automatically changes memory layout of the array so that it is appended to along the “growing axis”. However, if the memory layout needs adjusting, the array must reallocate and move memory.

The operation leaves the existing data in place and is most efficent if one of these is true:

  • The axis being appended to is the longest stride axis, i.e the array is in row major (“C”) layout.
  • The array has 0 or 1 rows (It is converted to row major)

Ensure appending is efficient by, for example, appending to an empty array and then always pushing/appending along the same axis. For pushing rows, ndarray’s default layout (C order) is efficient.

When repeatedly appending to a single axis, the amortized average complexity of each append is O(m), where m is the length of the row.

use ndarray::{Array, ArrayView, array};

// create an empty array and append
let mut a = Array::zeros((0, 4));
a.push_row(ArrayView::from(&[ 1.,  2.,  3.,  4.])).unwrap();
a.push_row(ArrayView::from(&[-1., -2., -3., -4.])).unwrap();

assert_eq!(
    a,
    array![[ 1.,  2.,  3.,  4.],
           [-1., -2., -3., -4.]]);
source

pub fn push_column( &mut self, column: ArrayView<'_, A, Ix1>, ) -> Result<(), ShapeError>
where A: Clone,

Append a column to an array

The elements from column are cloned and added as a new column in the array.

Errors with a shape error if the length of the column does not match the length of the columns in the array.

The memory layout of the self array matters for ensuring that the append is efficient. Appending automatically changes memory layout of the array so that it is appended to along the “growing axis”. However, if the memory layout needs adjusting, the array must reallocate and move memory.

The operation leaves the existing data in place and is most efficent if one of these is true:

  • The axis being appended to is the longest stride axis, i.e the array is in column major (“F”) layout.
  • The array has 0 or 1 columns (It is converted to column major)

Ensure appending is efficient by, for example, appending to an empty array and then always pushing/appending along the same axis. For pushing columns, column major layout (F order) is efficient.

When repeatedly appending to a single axis, the amortized average complexity of each append is O(m), where m is the length of the column.

use ndarray::{Array, ArrayView, array};

// create an empty array and append
let mut a = Array::zeros((2, 0));
a.push_column(ArrayView::from(&[1., 2.])).unwrap();
a.push_column(ArrayView::from(&[-1., -2.])).unwrap();

assert_eq!(
    a,
    array![[1., -1.],
           [2., -2.]]);
source

pub fn reserve_rows(&mut self, additional: usize) -> Result<(), ShapeError>

Reserve capacity to grow array by at least additional rows.

Existing elements of array are untouched and the backing storage is grown by calling the underlying reserve method of the OwnedRepr.

This is useful when pushing or appending repeatedly to an array to avoid multiple allocations.

Errors with a shape error if the resultant capacity is larger than the addressable bounds; that is, the product of non-zero axis lengths once axis has been extended by additional exceeds isize::MAX.

use ndarray::Array2;
let mut a = Array2::<i32>::zeros((2,4));
a.reserve_rows(1000).unwrap();
assert!(a.into_raw_vec().capacity() >= 4*1002);
source

pub fn reserve_columns(&mut self, additional: usize) -> Result<(), ShapeError>

Reserve capacity to grow array by at least additional columns.

Existing elements of array are untouched and the backing storage is grown by calling the underlying reserve method of the OwnedRepr.

This is useful when pushing or appending repeatedly to an array to avoid multiple allocations.

Errors with a shape error if the resultant capacity is larger than the addressable bounds; that is, the product of non-zero axis lengths once axis has been extended by additional exceeds isize::MAX.

use ndarray::Array2;
let mut a = Array2::<i32>::zeros((2,4));
a.reserve_columns(1000).unwrap();
assert!(a.into_raw_vec().capacity() >= 2*1002);
source§

impl<A, D> Array<A, D>
where D: Dimension,

source

pub fn move_into<'a, AM>(self, new_array: AM)
where AM: Into<ArrayViewMut<'a, A, D>>, A: 'a,

Move all elements from self into new_array, which must be of the same shape but can have a different memory layout. The destination is overwritten completely.

The destination should be a mut reference to an array or an ArrayViewMut with A elements.

Panics if the shapes don’t agree.

§Example
use ndarray::Array;

// Usage example of move_into in safe code
let mut a = Array::default((10, 10));
let b = Array::from_shape_fn((10, 10), |(i, j)| (i + j).to_string());
b.move_into(&mut a);
source

pub fn move_into_uninit<'a, AM>(self, new_array: AM)
where AM: Into<ArrayViewMut<'a, MaybeUninit<A>, D>>, A: 'a,

Move all elements from self into new_array, which must be of the same shape but can have a different memory layout. The destination is overwritten completely.

The destination should be a mut reference to an array or an ArrayViewMut with MaybeUninit<A> elements (which are overwritten without dropping any existing value).

Minor implementation note: Owned arrays like self may be sliced in place and own elements that are not part of their active view; these are dropped at the end of this function, after all elements in the “active view” are moved into new_array. If there is a panic in drop of any such element, other elements may be leaked.

Panics if the shapes don’t agree.

§Example
use ndarray::Array;

let a = Array::from_iter(0..100).into_shape_with_order((10, 10)).unwrap();
let mut b = Array::uninit((10, 10));
a.move_into_uninit(&mut b);
unsafe {
    // we can now promise we have fully initialized `b`.
    let b = b.assume_init();
}
source

pub fn push( &mut self, axis: Axis, array: ArrayView<'_, A, D::Smaller>, ) -> Result<(), ShapeError>
where A: Clone, D: RemoveAxis,

Append an array to the array along an axis.

The elements of array are cloned and extend the axis axis in the present array; self will grow in size by 1 along axis.

Append to the array, where the array being pushed to the array has one dimension less than the self array. This method is equivalent to append in this way: self.append(axis, array.insert_axis(axis)).

Errors with a shape error if the shape of self does not match the array-to-append; all axes except the axis along which it being appended matter for this check: the shape of self with axis removed must be the same as the shape of array.

The memory layout of the self array matters for ensuring that the append is efficient. Appending automatically changes memory layout of the array so that it is appended to along the “growing axis”. However, if the memory layout needs adjusting, the array must reallocate and move memory.

The operation leaves the existing data in place and is most efficent if axis is a “growing axis” for the array, i.e. one of these is true:

  • The axis is the longest stride axis, for example the 0th axis in a C-layout or the n-1th axis in an F-layout array.
  • The axis has length 0 or 1 (It is converted to the new growing axis)

Ensure appending is efficient by for example starting from an empty array and/or always appending to an array along the same axis.

The amortized average complexity of the append, when appending along its growing axis, is O(m) where m is the number of individual elements to append.

The memory layout of the argument array does not matter to the same extent.

use ndarray::{Array, ArrayView, array, Axis};

// create an empty array and push rows to it
let mut a = Array::zeros((0, 4));
let ones  = ArrayView::from(&[1.; 4]);
let zeros = ArrayView::from(&[0.; 4]);
a.push(Axis(0), ones).unwrap();
a.push(Axis(0), zeros).unwrap();
a.push(Axis(0), ones).unwrap();

assert_eq!(
    a,
    array![[1., 1., 1., 1.],
           [0., 0., 0., 0.],
           [1., 1., 1., 1.]]);
source

pub fn append( &mut self, axis: Axis, array: ArrayView<'_, A, D>, ) -> Result<(), ShapeError>
where A: Clone, D: RemoveAxis,

Append an array to the array along an axis.

The elements of array are cloned and extend the axis axis in the present array; self will grow in size by array.len_of(axis) along axis.

Errors with a shape error if the shape of self does not match the array-to-append; all axes except the axis along which it being appended matter for this check: the shape of self with axis removed must be the same as the shape of array with axis removed.

The memory layout of the self array matters for ensuring that the append is efficient. Appending automatically changes memory layout of the array so that it is appended to along the “growing axis”. However, if the memory layout needs adjusting, the array must reallocate and move memory.

The operation leaves the existing data in place and is most efficent if axis is a “growing axis” for the array, i.e. one of these is true:

  • The axis is the longest stride axis, for example the 0th axis in a C-layout or the n-1th axis in an F-layout array.
  • The axis has length 0 or 1 (It is converted to the new growing axis)

Ensure appending is efficient by for example starting from an empty array and/or always appending to an array along the same axis.

The amortized average complexity of the append, when appending along its growing axis, is O(m) where m is the number of individual elements to append.

The memory layout of the argument array does not matter to the same extent.

use ndarray::{Array, ArrayView, array, Axis};

// create an empty array and append two rows at a time
let mut a = Array::zeros((0, 4));
let ones  = ArrayView::from(&[1.; 8]).into_shape_with_order((2, 4)).unwrap();
let zeros = ArrayView::from(&[0.; 8]).into_shape_with_order((2, 4)).unwrap();
a.append(Axis(0), ones).unwrap();
a.append(Axis(0), zeros).unwrap();
a.append(Axis(0), ones).unwrap();

assert_eq!(
    a,
    array![[1., 1., 1., 1.],
           [1., 1., 1., 1.],
           [0., 0., 0., 0.],
           [0., 0., 0., 0.],
           [1., 1., 1., 1.],
           [1., 1., 1., 1.]]);
source

pub fn reserve( &mut self, axis: Axis, additional: usize, ) -> Result<(), ShapeError>
where D: RemoveAxis,

Reserve capacity to grow array along axis by at least additional elements.

The axis should be in the range Axis( 0 .. n ) where n is the number of dimensions (axes) of the array.

Existing elements of array are untouched and the backing storage is grown by calling the underlying reserve method of the OwnedRepr.

This is useful when pushing or appending repeatedly to an array to avoid multiple allocations.

Panics if the axis is out of bounds.

Errors with a shape error if the resultant capacity is larger than the addressable bounds; that is, the product of non-zero axis lengths once axis has been extended by additional exceeds isize::MAX.

use ndarray::{Array3, Axis};
let mut a = Array3::<i32>::zeros((0,2,4));
a.reserve(Axis(0), 1000).unwrap();
assert!(a.into_raw_vec().capacity() >= 2*4*1000);

Trait Implementations§

source§

impl<A, const N: usize, const M: usize, const L: usize, const K: usize, const J: usize> From<Vec<[[[[[A; J]; K]; L]; M]; N]>> for Array<A, Ix6>

source§

fn from(xs: Vec<[[[[[A; J]; K]; L]; M]; N]>) -> Self

Converts to this type from the input type.
source§

impl<A, const N: usize, const M: usize, const L: usize, const K: usize> From<Vec<[[[[A; K]; L]; M]; N]>> for Array<A, Ix5>

source§

fn from(xs: Vec<[[[[A; K]; L]; M]; N]>) -> Self

Converts to this type from the input type.
source§

impl<A, const N: usize, const M: usize, const L: usize> From<Vec<[[[A; L]; M]; N]>> for Array<A, Ix4>

source§

fn from(xs: Vec<[[[A; L]; M]; N]>) -> Self

Converts to this type from the input type.
source§

impl<A, const N: usize, const M: usize> From<Vec<[[A; M]; N]>> for Array<A, Ix3>

source§

fn from(xs: Vec<[[A; M]; N]>) -> Self

Converts to this type from the input type.
source§

impl<A, const N: usize> From<Vec<[A; N]>> for Array<A, Ix2>

source§

fn from(xs: Vec<[A; N]>) -> Self

Converts to this type from the input type.
source§

impl<A, D> IntoIterator for Array<A, D>
where D: Dimension,

§

type Item = A

The type of the elements being iterated over.
§

type IntoIter = IntoIter<A, D>

Which kind of iterator are we turning this into?
source§

fn into_iter(self) -> Self::IntoIter

Creates an iterator from a value. Read more
source§

impl<'a, A, D> IntoParallelIterator for &'a Array<A, D>
where D: Dimension, A: Sync,

Requires crate feature rayon.

§

type Item = &'a A

The type of item that the parallel iterator will produce.
§

type Iter = Parallel<ArrayBase<ViewRepr<&'a A>, D>>

The parallel iterator type that will be created.
source§

fn into_par_iter(self) -> Self::Iter

Converts self into a parallel iterator. Read more
source§

impl<'a, A, D> IntoParallelIterator for &'a mut Array<A, D>
where D: Dimension, A: Sync + Send,

Requires crate feature rayon.

§

type Item = &'a mut A

The type of item that the parallel iterator will produce.
§

type Iter = Parallel<ArrayBase<ViewRepr<&'a mut A>, D>>

The parallel iterator type that will be created.
source§

fn into_par_iter(self) -> Self::Iter

Converts self into a parallel iterator. Read more