[−]Struct lumol::Array2
Two dimensional tensors, based on ndarray.
Most of the methods are simply forwarded to ndarray, so also look the doc for this crate. This array type mainly supports indexing using tuples as indices and is though as storage backend for multi-dimensional data.
let mut a = Array2::zeros((3, 5)); assert_eq!(a[(0, 4)], 0.0); a[(0, 4)] = 7.0; assert_eq!(a[(0, 4)], 7.0);
Implementations
impl<T> Array2<T> where
T: Clone + Zero,
T: Clone + Zero,
pub fn zeros(size: (usize, usize)) -> Array2<T>
Create a new Array2
of the specified size
filled with the
Zero::zero
return value.
Examples
let a: Array2<f64> = Array2::zeros((8, 5)); assert_eq!(a[(6, 2)], 0.0);
pub fn resize_if_different(&mut self, size: (usize, usize))
Resize the array if the current size is not size
, and fill the
new array with zeros.
Examples
let mut a = Array2::zeros((8, 5)); a[(3, 3)] = 42.0; // This does nothing a.resize_if_different((8, 5)); assert_eq!(a[(3, 3)], 42.0); // This allocates a new array a.resize_if_different((8, 9)); assert_eq!(a[(3, 3)], 0.0);
impl<T> Array2<T> where
T: Default,
T: Default,
pub fn default(size: (usize, usize)) -> Array2<T>
Create a new Array2
of the specified size
filled with the
Default::default
return value.
Examples
let a: Array2<f64> = Array2::zeros((8, 5)); let b: Array2<f64> = Array2::default((8, 5)); assert_eq!(a, b);
Methods from Deref<Target = ArrayBase<OwnedRepr<T>, Dim<[usize; 2]>>>
pub fn len(&self) -> usize
[src]
Return the total number of elements in the array.
pub fn len_of(&self, axis: Axis) -> usize
[src]
Return the length of axis
.
The axis should be in the range Axis(
0 .. n )
where n is the
number of dimensions (axes) of the array.
Panics if the axis is out of bounds.
pub fn is_empty(&self) -> bool
[src]
Return whether the array has any elements
pub fn ndim(&self) -> usize
[src]
Return the number of dimensions (axes) in the array
pub fn dim(&self) -> <D as Dimension>::Pattern
[src]
Return the shape of the array in its “pattern” form, an integer in the one-dimensional case, tuple in the n-dimensional cases and so on.
pub fn raw_dim(&self) -> D
[src]
Return the shape of the array as it stored in the array.
This is primarily useful for passing to other ArrayBase
functions, such as when creating another array of the same
shape and dimensionality.
use ndarray::Array; let a = Array::from_elem((2, 3), 5.); // Create an array of zeros that's the same shape and dimensionality as `a`. let b = Array::<f64, _>::zeros(a.raw_dim());
pub fn shape(&self) -> &[usize]
[src]
Return the shape of the array as a slice.
Note that you probably don't want to use this to create an array of the
same shape as another array because creating an array with e.g.
Array::zeros()
using a shape of type &[usize]
results in a dynamic-dimensional array. If you want to create an array
that has the same shape and dimensionality as another array, use
.raw_dim()
instead:
use ndarray::{Array, Array2}; let a = Array2::<i32>::zeros((3, 4)); let shape = a.shape(); assert_eq!(shape, &[3, 4]); // Since `a.shape()` returned `&[usize]`, we get an `ArrayD` instance: let b = Array::zeros(shape); assert_eq!(a.clone().into_dyn(), b); // To get the same dimension type, use `.raw_dim()` instead: let c = Array::zeros(a.raw_dim()); assert_eq!(a, c);
pub fn strides(&self) -> &[isize]
[src]
Return the strides of the array as a slice.
pub fn stride_of(&self, axis: Axis) -> isize
[src]
Return the stride of axis
.
The axis should be in the range Axis(
0 .. n )
where n is the
number of dimensions (axes) of the array.
Panics if the axis is out of bounds.
pub fn view(&self) -> ArrayBase<ViewRepr<&A>, D> where
S: Data,
[src]
S: Data,
Return a read-only view of the array
pub fn view_mut(&mut self) -> ArrayBase<ViewRepr<&mut A>, D> where
S: DataMut,
[src]
S: DataMut,
Return a read-write view of the array
pub fn to_owned(&self) -> ArrayBase<OwnedRepr<A>, D> where
A: Clone,
S: Data,
[src]
A: Clone,
S: Data,
Return an uniquely owned copy of the array.
If the input array is contiguous and its strides are positive, then the
output array will have the same memory layout. Otherwise, the layout of
the output array is unspecified. If you need a particular layout, you
can allocate a new array with the desired memory layout and
.assign()
the data. Alternatively, you can collect
an iterator, like this for a result in standard layout:
Array::from_shape_vec(arr.raw_dim(), arr.iter().cloned().collect()).unwrap()
or this for a result in column-major (Fortran) layout:
Array::from_shape_vec(arr.raw_dim().f(), arr.t().iter().cloned().collect()).unwrap()
pub fn to_shared(&self) -> ArrayBase<OwnedArcRepr<A>, D> where
A: Clone,
S: Data,
[src]
A: Clone,
S: Data,
Return a shared ownership (copy on write) array.
pub fn first(&self) -> Option<&A> where
S: Data,
[src]
S: Data,
Returns a reference to the first element of the array, or None
if it
is empty.
pub fn first_mut(&mut self) -> Option<&mut A> where
S: DataMut,
[src]
S: DataMut,
Returns a mutable reference to the first element of the array, or
None
if it is empty.
pub fn iter(&self) -> Iter<'_, A, D> where
S: Data,
[src]
S: Data,
Return an iterator of references to the elements of the array.
Elements are visited in the logical order of the array, which is where the rightmost index is varying the fastest.
Iterator element type is &A
.
pub fn iter_mut(&mut self) -> IterMut<'_, A, D> where
S: DataMut,
[src]
S: DataMut,
Return an iterator of mutable references to the elements of the array.
Elements are visited in the logical order of the array, which is where the rightmost index is varying the fastest.
Iterator element type is &mut A
.
pub fn indexed_iter(&self) -> IndexedIter<'_, A, D> where
S: Data,
[src]
S: Data,
Return an iterator of indexes and references to the elements of the array.
Elements are visited in the logical order of the array, which is where the rightmost index is varying the fastest.
Iterator element type is (D::Pattern, &A)
.
See also Zip::indexed
pub fn indexed_iter_mut(&mut self) -> IndexedIterMut<'_, A, D> where
S: DataMut,
[src]
S: DataMut,
Return an iterator of indexes and mutable references to the elements of the array.
Elements are visited in the logical order of the array, which is where the rightmost index is varying the fastest.
Iterator element type is (D::Pattern, &mut A)
.
pub fn slice<Do>(
&self,
info: &SliceInfo<<D as Dimension>::SliceArg, Do>
) -> ArrayBase<ViewRepr<&A>, Do> where
Do: Dimension,
S: Data,
[src]
&self,
info: &SliceInfo<<D as Dimension>::SliceArg, Do>
) -> ArrayBase<ViewRepr<&A>, Do> where
Do: Dimension,
S: Data,
Return a sliced view of the array.
See Slicing for full documentation.
See also SliceInfo
and D::SliceArg
.
Panics if an index is out of bounds or step size is zero.
(Panics if D
is IxDyn
and info
does not match the number of array axes.)
pub fn slice_mut<Do>(
&mut self,
info: &SliceInfo<<D as Dimension>::SliceArg, Do>
) -> ArrayBase<ViewRepr<&mut A>, Do> where
Do: Dimension,
S: DataMut,
[src]
&mut self,
info: &SliceInfo<<D as Dimension>::SliceArg, Do>
) -> ArrayBase<ViewRepr<&mut A>, Do> where
Do: Dimension,
S: DataMut,
Return a sliced read-write view of the array.
See Slicing for full documentation.
See also SliceInfo
and D::SliceArg
.
Panics if an index is out of bounds or step size is zero.
(Panics if D
is IxDyn
and info
does not match the number of array axes.)
pub fn multi_slice_mut<'a, M>(
&'a mut self,
info: M
) -> <M as MultiSlice<'a, A, D>>::Output where
M: MultiSlice<'a, A, D>,
S: DataMut,
[src]
&'a mut self,
info: M
) -> <M as MultiSlice<'a, A, D>>::Output where
M: MultiSlice<'a, A, D>,
S: DataMut,
Return multiple disjoint, sliced, mutable views of the array.
See Slicing for full documentation.
See also SliceInfo
and D::SliceArg
.
Panics if any of the following occur:
- if any of the views would intersect (i.e. if any element would appear in multiple slices)
- if an index is out of bounds or step size is zero
- if
D
isIxDyn
andinfo
does not match the number of array axes
Example
use ndarray::{arr2, s}; let mut a = arr2(&[[1, 2, 3], [4, 5, 6]]); let (mut edges, mut middle) = a.multi_slice_mut((s![.., ..;2], s![.., 1])); edges.fill(1); middle.fill(0); assert_eq!(a, arr2(&[[1, 0, 1], [1, 0, 1]]));
pub fn slice_collapse(&mut self, indices: &<D as Dimension>::SliceArg)
[src]
Slice the array in place without changing the number of dimensions.
Note that &SliceInfo
(produced by the
s![]
macro) will usually coerce into &D::SliceArg
automatically, but in some cases (e.g. if D
is IxDyn
), you may need
to call .as_ref()
.
See Slicing for full documentation.
See also D::SliceArg
.
Panics if an index is out of bounds or step size is zero.
(Panics if D
is IxDyn
and indices
does not match the number of array axes.)
pub fn slice_axis(
&self,
axis: Axis,
indices: Slice
) -> ArrayBase<ViewRepr<&A>, D> where
S: Data,
[src]
&self,
axis: Axis,
indices: Slice
) -> ArrayBase<ViewRepr<&A>, D> where
S: Data,
Return a view of the array, sliced along the specified axis.
Panics if an index is out of bounds or step size is zero.
Panics if axis
is out of bounds.
pub fn slice_axis_mut(
&mut self,
axis: Axis,
indices: Slice
) -> ArrayBase<ViewRepr<&mut A>, D> where
S: DataMut,
[src]
&mut self,
axis: Axis,
indices: Slice
) -> ArrayBase<ViewRepr<&mut A>, D> where
S: DataMut,
Return a mutable view of the array, sliced along the specified axis.
Panics if an index is out of bounds or step size is zero.
Panics if axis
is out of bounds.
pub fn slice_axis_inplace(&mut self, axis: Axis, indices: Slice)
[src]
Slice the array in place along the specified axis.
Panics if an index is out of bounds or step size is zero.
Panics if axis
is out of bounds.
pub fn get<I>(&self, index: I) -> Option<&A> where
I: NdIndex<D>,
S: Data,
[src]
I: NdIndex<D>,
S: Data,
Return a reference to the element at index
, or return None
if the index is out of bounds.
Arrays also support indexing syntax: array[index]
.
use ndarray::arr2; let a = arr2(&[[1., 2.], [3., 4.]]); assert!( a.get((0, 1)) == Some(&2.) && a.get((0, 2)) == None && a[(0, 1)] == 2. && a[[0, 1]] == 2. );
pub fn get_mut<I>(&mut self, index: I) -> Option<&mut A> where
I: NdIndex<D>,
S: DataMut,
[src]
I: NdIndex<D>,
S: DataMut,
Return a mutable reference to the element at index
, or return None
if the index is out of bounds.
pub unsafe fn uget<I>(&self, index: I) -> &A where
I: NdIndex<D>,
S: Data,
[src]
I: NdIndex<D>,
S: Data,
Perform unchecked array indexing.
Return a reference to the element at index
.
Note: only unchecked for non-debug builds of ndarray.
Safety
The caller must ensure that the index is in-bounds.
pub unsafe fn uget_mut<I>(&mut self, index: I) -> &mut A where
I: NdIndex<D>,
S: DataMut,
[src]
I: NdIndex<D>,
S: DataMut,
Perform unchecked array indexing.
Return a mutable reference to the element at index
.
Note: Only unchecked for non-debug builds of ndarray.
Safety
The caller must ensure that:
-
the index is in-bounds and
-
the data is uniquely held by the array. (This property is guaranteed for
Array
andArrayViewMut
, but not forArcArray
orCowArray
.)
pub fn swap<I>(&mut self, index1: I, index2: I) where
I: NdIndex<D>,
S: DataMut,
[src]
I: NdIndex<D>,
S: DataMut,
Swap elements at indices index1
and index2
.
Indices may be equal.
Panics if an index is out of bounds.
pub unsafe fn uswap<I>(&mut self, index1: I, index2: I) where
I: NdIndex<D>,
S: DataMut,
[src]
I: NdIndex<D>,
S: DataMut,
Swap elements unchecked at indices index1
and index2
.
Indices may be equal.
Note: only unchecked for non-debug builds of ndarray.
Safety
The caller must ensure that:
-
both
index1 and
index2` are in-bounds and -
the data is uniquely held by the array. (This property is guaranteed for
Array
andArrayViewMut
, but not forArcArray
orCowArray
.)
pub fn index_axis(
&self,
axis: Axis,
index: usize
) -> ArrayBase<ViewRepr<&A>, <D as Dimension>::Smaller> where
D: RemoveAxis,
S: Data,
[src]
&self,
axis: Axis,
index: usize
) -> ArrayBase<ViewRepr<&A>, <D as Dimension>::Smaller> where
D: RemoveAxis,
S: Data,
Returns a view restricted to index
along the axis, with the axis
removed.
See Subviews for full documentation.
Panics if axis
or index
is out of bounds.
use ndarray::{arr2, ArrayView, Axis}; let a = arr2(&[[1., 2. ], // ... axis 0, row 0 [3., 4. ], // --- axis 0, row 1 [5., 6. ]]); // ... axis 0, row 2 // . \ // . axis 1, column 1 // axis 1, column 0 assert!( a.index_axis(Axis(0), 1) == ArrayView::from(&[3., 4.]) && a.index_axis(Axis(1), 1) == ArrayView::from(&[2., 4., 6.]) );
pub fn index_axis_mut(
&mut self,
axis: Axis,
index: usize
) -> ArrayBase<ViewRepr<&mut A>, <D as Dimension>::Smaller> where
D: RemoveAxis,
S: DataMut,
[src]
&mut self,
axis: Axis,
index: usize
) -> ArrayBase<ViewRepr<&mut A>, <D as Dimension>::Smaller> where
D: RemoveAxis,
S: DataMut,
Returns a mutable view restricted to index
along the axis, with the
axis removed.
Panics if axis
or index
is out of bounds.
use ndarray::{arr2, aview2, Axis}; let mut a = arr2(&[[1., 2. ], [3., 4. ]]); // . \ // . axis 1, column 1 // axis 1, column 0 { let mut column1 = a.index_axis_mut(Axis(1), 1); column1 += 10.; } assert!( a == aview2(&[[1., 12.], [3., 14.]]) );
pub fn collapse_axis(&mut self, axis: Axis, index: usize)
[src]
Selects index
along the axis, collapsing the axis into length one.
Panics if axis
or index
is out of bounds.
pub fn select(
&self,
axis: Axis,
indices: &[usize]
) -> ArrayBase<OwnedRepr<A>, D> where
A: Copy,
D: RemoveAxis,
S: Data,
[src]
&self,
axis: Axis,
indices: &[usize]
) -> ArrayBase<OwnedRepr<A>, D> where
A: Copy,
D: RemoveAxis,
S: Data,
Along axis
, select arbitrary subviews corresponding to indices
and and copy them into a new array.
Panics if axis
or an element of indices
is out of bounds.
use ndarray::{arr2, Axis}; let x = arr2(&[[0., 1.], [2., 3.], [4., 5.], [6., 7.], [8., 9.]]); let r = x.select(Axis(0), &[0, 4, 3]); assert!( r == arr2(&[[0., 1.], [8., 9.], [6., 7.]]) );
pub fn genrows(&self) -> Lanes<'_, A, <D as Dimension>::Smaller> where
S: Data,
[src]
S: Data,
Return a producer and iterable that traverses over the generalized rows of the array. For a 2D array these are the regular rows.
This is equivalent to .lanes(Axis(n - 1))
where n is self.ndim()
.
For an array of dimensions a × b × c × ... × l × m it has a × b × c × ... × l rows each of length m.
For example, in a 2 × 2 × 3 array, each row is 3 elements long and there are 2 × 2 = 4 rows in total.
Iterator element is ArrayView1<A>
(1D array view).
use ndarray::{arr3, Axis, arr1}; let a = arr3(&[[[ 0, 1, 2], // -- row 0, 0 [ 3, 4, 5]], // -- row 0, 1 [[ 6, 7, 8], // -- row 1, 0 [ 9, 10, 11]]]); // -- row 1, 1 // `genrows` will yield the four generalized rows of the array. for row in a.genrows() { /* loop body */ }
pub fn genrows_mut(&mut self) -> LanesMut<'_, A, <D as Dimension>::Smaller> where
S: DataMut,
[src]
S: DataMut,
Return a producer and iterable that traverses over the generalized rows of the array and yields mutable array views.
Iterator element is ArrayView1<A>
(1D read-write array view).
pub fn gencolumns(&self) -> Lanes<'_, A, <D as Dimension>::Smaller> where
S: Data,
[src]
S: Data,
Return a producer and iterable that traverses over the generalized columns of the array. For a 2D array these are the regular columns.
This is equivalent to .lanes(Axis(0))
.
For an array of dimensions a × b × c × ... × l × m it has b × c × ... × l × m columns each of length a.
For example, in a 2 × 2 × 3 array, each column is 2 elements long and there are 2 × 3 = 6 columns in total.
Iterator element is ArrayView1<A>
(1D array view).
use ndarray::{arr3, Axis, arr1}; // The generalized columns of a 3D array: // are directed along the 0th axis: 0 and 6, 1 and 7 and so on... let a = arr3(&[[[ 0, 1, 2], [ 3, 4, 5]], [[ 6, 7, 8], [ 9, 10, 11]]]); // Here `gencolumns` will yield the six generalized columns of the array. for row in a.gencolumns() { /* loop body */ }
pub fn gencolumns_mut(&mut self) -> LanesMut<'_, A, <D as Dimension>::Smaller> where
S: DataMut,
[src]
S: DataMut,
Return a producer and iterable that traverses over the generalized columns of the array and yields mutable array views.
Iterator element is ArrayView1<A>
(1D read-write array view).
pub fn lanes(&self, axis: Axis) -> Lanes<'_, A, <D as Dimension>::Smaller> where
S: Data,
[src]
S: Data,
Return a producer and iterable that traverses over all 1D lanes
pointing in the direction of axis
.
When the pointing in the direction of the first axis, they are columns, in the direction of the last axis rows; in general they are all lanes and are one dimensional.
Iterator element is ArrayView1<A>
(1D array view).
use ndarray::{arr3, aview1, Axis}; let a = arr3(&[[[ 0, 1, 2], [ 3, 4, 5]], [[ 6, 7, 8], [ 9, 10, 11]]]); let inner0 = a.lanes(Axis(0)); let inner1 = a.lanes(Axis(1)); let inner2 = a.lanes(Axis(2)); // The first lane for axis 0 is [0, 6] assert_eq!(inner0.into_iter().next().unwrap(), aview1(&[0, 6])); // The first lane for axis 1 is [0, 3] assert_eq!(inner1.into_iter().next().unwrap(), aview1(&[0, 3])); // The first lane for axis 2 is [0, 1, 2] assert_eq!(inner2.into_iter().next().unwrap(), aview1(&[0, 1, 2]));
pub fn lanes_mut(
&mut self,
axis: Axis
) -> LanesMut<'_, A, <D as Dimension>::Smaller> where
S: DataMut,
[src]
&mut self,
axis: Axis
) -> LanesMut<'_, A, <D as Dimension>::Smaller> where
S: DataMut,
Return a producer and iterable that traverses over all 1D lanes
pointing in the direction of axis
.
Iterator element is ArrayViewMut1<A>
(1D read-write array view).
pub fn outer_iter(&self) -> AxisIter<'_, A, <D as Dimension>::Smaller> where
D: RemoveAxis,
S: Data,
[src]
D: RemoveAxis,
S: Data,
Return an iterator that traverses over the outermost dimension and yields each subview.
This is equivalent to .axis_iter(Axis(0))
.
Iterator element is ArrayView<A, D::Smaller>
(read-only array view).
pub fn outer_iter_mut(
&mut self
) -> AxisIterMut<'_, A, <D as Dimension>::Smaller> where
D: RemoveAxis,
S: DataMut,
[src]
&mut self
) -> AxisIterMut<'_, A, <D as Dimension>::Smaller> where
D: RemoveAxis,
S: DataMut,
Return an iterator that traverses over the outermost dimension and yields each subview.
This is equivalent to .axis_iter_mut(Axis(0))
.
Iterator element is ArrayViewMut<A, D::Smaller>
(read-write array view).
pub fn axis_iter(
&self,
axis: Axis
) -> AxisIter<'_, A, <D as Dimension>::Smaller> where
D: RemoveAxis,
S: Data,
[src]
&self,
axis: Axis
) -> AxisIter<'_, A, <D as Dimension>::Smaller> where
D: RemoveAxis,
S: Data,
Return an iterator that traverses over axis
and yields each subview along it.
For example, in a 3 × 4 × 5 array, with axis
equal to Axis(2)
,
the iterator element
is a 3 × 4 subview (and there are 5 in total), as shown
in the picture below.
Iterator element is ArrayView<A, D::Smaller>
(read-only array view).
See Subviews for full documentation.
Panics if axis
is out of bounds.
pub fn axis_iter_mut(
&mut self,
axis: Axis
) -> AxisIterMut<'_, A, <D as Dimension>::Smaller> where
D: RemoveAxis,
S: DataMut,
[src]
&mut self,
axis: Axis
) -> AxisIterMut<'_, A, <D as Dimension>::Smaller> where
D: RemoveAxis,
S: DataMut,
Return an iterator that traverses over axis
and yields each mutable subview along it.
Iterator element is ArrayViewMut<A, D::Smaller>
(read-write array view).
Panics if axis
is out of bounds.
pub fn axis_chunks_iter(
&self,
axis: Axis,
size: usize
) -> AxisChunksIter<'_, A, D> where
S: Data,
[src]
&self,
axis: Axis,
size: usize
) -> AxisChunksIter<'_, A, D> where
S: Data,
Return an iterator that traverses over axis
by chunks of size
,
yielding non-overlapping views along that axis.
Iterator element is ArrayView<A, D>
The last view may have less elements if size
does not divide
the axis' dimension.
Panics if axis
is out of bounds or if size
is zero.
use ndarray::Array; use ndarray::{arr3, Axis}; use std::iter::FromIterator; let a = Array::from_iter(0..28).into_shape((2, 7, 2)).unwrap(); let mut iter = a.axis_chunks_iter(Axis(1), 2); // first iteration yields a 2 × 2 × 2 view assert_eq!(iter.next().unwrap(), arr3(&[[[ 0, 1], [ 2, 3]], [[14, 15], [16, 17]]])); // however the last element is a 2 × 1 × 2 view since 7 % 2 == 1 assert_eq!(iter.next_back().unwrap(), arr3(&[[[12, 13]], [[26, 27]]]));
pub fn axis_chunks_iter_mut(
&mut self,
axis: Axis,
size: usize
) -> AxisChunksIterMut<'_, A, D> where
S: DataMut,
[src]
&mut self,
axis: Axis,
size: usize
) -> AxisChunksIterMut<'_, A, D> where
S: DataMut,
Return an iterator that traverses over axis
by chunks of size
,
yielding non-overlapping read-write views along that axis.
Iterator element is ArrayViewMut<A, D>
Panics if axis
is out of bounds or if size
is zero.
pub fn exact_chunks<E>(&self, chunk_size: E) -> ExactChunks<'_, A, D> where
E: IntoDimension<Dim = D>,
S: Data,
[src]
E: IntoDimension<Dim = D>,
S: Data,
Return an exact chunks producer (and iterable).
It produces the whole chunks of a given n-dimensional chunk size, skipping the remainder along each dimension that doesn't fit evenly.
The produced element is a ArrayView<A, D>
with exactly the dimension
chunk_size
.
Panics if any dimension of chunk_size
is zero
(Panics if D
is IxDyn
and chunk_size
does not match the
number of array axes.)
pub fn exact_chunks_mut<E>(&mut self, chunk_size: E) -> ExactChunksMut<'_, A, D> where
E: IntoDimension<Dim = D>,
S: DataMut,
[src]
E: IntoDimension<Dim = D>,
S: DataMut,
Return an exact chunks producer (and iterable).
It produces the whole chunks of a given n-dimensional chunk size, skipping the remainder along each dimension that doesn't fit evenly.
The produced element is a ArrayViewMut<A, D>
with exactly
the dimension chunk_size
.
Panics if any dimension of chunk_size
is zero
(Panics if D
is IxDyn
and chunk_size
does not match the
number of array axes.)
use ndarray::Array; use ndarray::arr2; let mut a = Array::zeros((6, 7)); // Fill each 2 × 2 chunk with the index of where it appeared in iteration for (i, mut chunk) in a.exact_chunks_mut((2, 2)).into_iter().enumerate() { chunk.fill(i); } // The resulting array is: assert_eq!( a, arr2(&[[0, 0, 1, 1, 2, 2, 0], [0, 0, 1, 1, 2, 2, 0], [3, 3, 4, 4, 5, 5, 0], [3, 3, 4, 4, 5, 5, 0], [6, 6, 7, 7, 8, 8, 0], [6, 6, 7, 7, 8, 8, 0]]));
pub fn windows<E>(&self, window_size: E) -> Windows<'_, A, D> where
E: IntoDimension<Dim = D>,
S: Data,
[src]
E: IntoDimension<Dim = D>,
S: Data,
Return a window producer and iterable.
The windows are all distinct overlapping views of size window_size
that fit into the array's shape.
Will yield over no elements if window size is larger than the actual array size of any dimension.
The produced element is an ArrayView<A, D>
with exactly the dimension
window_size
.
Panics if any dimension of window_size
is zero.
(Panics if D
is IxDyn
and window_size
does not match the
number of array axes.)
This is an illustration of the 2×2 windows in a 3×4 array:
──▶ Axis(1)
│ ┏━━━━━┳━━━━━┱─────┬─────┐ ┌─────┲━━━━━┳━━━━━┱─────┐ ┌─────┬─────┲━━━━━┳━━━━━┓
▼ ┃ a₀₀ ┃ a₀₁ ┃ │ │ │ ┃ a₀₁ ┃ a₀₂ ┃ │ │ │ ┃ a₀₂ ┃ a₀₃ ┃
Axis(0) ┣━━━━━╋━━━━━╉─────┼─────┤ ├─────╊━━━━━╋━━━━━╉─────┤ ├─────┼─────╊━━━━━╋━━━━━┫
┃ a₁₀ ┃ a₁₁ ┃ │ │ │ ┃ a₁₁ ┃ a₁₂ ┃ │ │ │ ┃ a₁₂ ┃ a₁₃ ┃
┡━━━━━╇━━━━━╃─────┼─────┤ ├─────╄━━━━━╇━━━━━╃─────┤ ├─────┼─────╄━━━━━╇━━━━━┩
│ │ │ │ │ │ │ │ │ │ │ │ │ │ │
└─────┴─────┴─────┴─────┘ └─────┴─────┴─────┴─────┘ └─────┴─────┴─────┴─────┘
┌─────┬─────┬─────┬─────┐ ┌─────┬─────┬─────┬─────┐ ┌─────┬─────┬─────┬─────┐
│ │ │ │ │ │ │ │ │ │ │ │ │ │ │
┢━━━━━╈━━━━━╅─────┼─────┤ ├─────╆━━━━━╈━━━━━╅─────┤ ├─────┼─────╆━━━━━╈━━━━━┪
┃ a₁₀ ┃ a₁₁ ┃ │ │ │ ┃ a₁₁ ┃ a₁₂ ┃ │ │ │ ┃ a₁₂ ┃ a₁₃ ┃
┣━━━━━╋━━━━━╉─────┼─────┤ ├─────╊━━━━━╋━━━━━╉─────┤ ├─────┼─────╊━━━━━╋━━━━━┫
┃ a₂₀ ┃ a₂₁ ┃ │ │ │ ┃ a₂₁ ┃ a₂₂ ┃ │ │ │ ┃ a₂₂ ┃ a₂₃ ┃
┗━━━━━┻━━━━━┹─────┴─────┘ └─────┺━━━━━┻━━━━━┹─────┘ └─────┴─────┺━━━━━┻━━━━━┛
pub fn diag(&self) -> ArrayBase<ViewRepr<&A>, Dim<[usize; 1]>> where
S: Data,
[src]
S: Data,
Return an view of the diagonal elements of the array.
The diagonal is simply the sequence indexed by (0, 0, .., 0), (1, 1, ..., 1) etc as long as all axes have elements.
pub fn diag_mut(&mut self) -> ArrayBase<ViewRepr<&mut A>, Dim<[usize; 1]>> where
S: DataMut,
[src]
S: DataMut,
Return a read-write view over the diagonal elements of the array.
pub fn is_standard_layout(&self) -> bool
[src]
Return true
if the array data is laid out in contiguous “C order” in
memory (where the last index is the most rapidly varying).
Return false
otherwise, i.e the array is possibly not
contiguous in memory, it has custom strides, etc.
pub fn as_standard_layout(&self) -> ArrayBase<CowRepr<'_, A>, D> where
A: Clone,
S: Data<Elem = A>,
[src]
A: Clone,
S: Data<Elem = A>,
Return a standard-layout array containing the data, cloning if necessary.
If self
is in standard layout, a COW view of the data is returned
without cloning. Otherwise, the data is cloned, and the returned array
owns the cloned data.
use ndarray::Array2; let standard = Array2::<f64>::zeros((3, 4)); assert!(standard.is_standard_layout()); let cow_view = standard.as_standard_layout(); assert!(cow_view.is_view()); assert!(cow_view.is_standard_layout()); let fortran = standard.reversed_axes(); assert!(!fortran.is_standard_layout()); let cow_owned = fortran.as_standard_layout(); assert!(cow_owned.is_owned()); assert!(cow_owned.is_standard_layout());
pub fn as_ptr(&self) -> *const A
[src]
Return a pointer to the first element in the array.
Raw access to array elements needs to follow the strided indexing scheme: an element at multi-index I in an array with strides S is located at offset
Σ0 ≤ k < d Ik × Sk
where d is self.ndim()
.
pub fn as_mut_ptr(&mut self) -> *mut A where
S: RawDataMut,
[src]
S: RawDataMut,
Return a mutable pointer to the first element in the array.
pub fn raw_view(&self) -> ArrayBase<RawViewRepr<*const A>, D>
[src]
Return a raw view of the array.
pub fn raw_view_mut(&mut self) -> ArrayBase<RawViewRepr<*mut A>, D> where
S: RawDataMut,
[src]
S: RawDataMut,
Return a raw mutable view of the array.
pub fn as_slice(&self) -> Option<&[A]> where
S: Data,
[src]
S: Data,
Return the array’s data as a slice, if it is contiguous and in standard order.
Return None
otherwise.
If this function returns Some(_)
, then the element order in the slice
corresponds to the logical order of the array’s elements.
pub fn as_slice_mut(&mut self) -> Option<&mut [A]> where
S: DataMut,
[src]
S: DataMut,
Return the array’s data as a slice, if it is contiguous and in standard order.
Return None
otherwise.
pub fn as_slice_memory_order(&self) -> Option<&[A]> where
S: Data,
[src]
S: Data,
Return the array’s data as a slice if it is contiguous,
return None
otherwise.
If this function returns Some(_)
, then the elements in the slice
have whatever order the elements have in memory.
Implementation notes: Does not yet support negatively strided arrays.
pub fn as_slice_memory_order_mut(&mut self) -> Option<&mut [A]> where
S: DataMut,
[src]
S: DataMut,
Return the array’s data as a slice if it is contiguous,
return None
otherwise.
pub fn reshape<E>(&self, shape: E) -> ArrayBase<S, <E as IntoDimension>::Dim> where
A: Clone,
E: IntoDimension,
S: DataShared + DataOwned,
[src]
A: Clone,
E: IntoDimension,
S: DataShared + DataOwned,
Note: Reshape is for ArcArray
only. Use .into_shape()
for
other arrays and array views.
Transform the array into shape
; any shape with the same number of
elements is accepted.
May clone all elements if needed to arrange elements in standard layout (and break sharing).
Panics if shapes are incompatible.
use ndarray::{rcarr1, rcarr2}; assert!( rcarr1(&[1., 2., 3., 4.]).reshape((2, 2)) == rcarr2(&[[1., 2.], [3., 4.]]) );
pub fn broadcast<E>(
&self,
dim: E
) -> Option<ArrayBase<ViewRepr<&A>, <E as IntoDimension>::Dim>> where
E: IntoDimension,
S: Data,
[src]
&self,
dim: E
) -> Option<ArrayBase<ViewRepr<&A>, <E as IntoDimension>::Dim>> where
E: IntoDimension,
S: Data,
Act like a larger size and/or shape array by broadcasting into a larger shape, if possible.
Return None
if shapes can not be broadcast together.
Background
- Two axes are compatible if they are equal, or one of them is 1.
- In this instance, only the axes of the smaller side (self) can be 1.
Compare axes beginning with the last axis of each shape.
For example (1, 2, 4) can be broadcast into (7, 6, 2, 4) because its axes are either equal or 1 (or missing); while (2, 2) can not be broadcast into (2, 4).
The implementation creates a view with strides set to zero for the axes that are to be repeated.
The broadcasting documentation for Numpy has more information.
use ndarray::{aview1, aview2}; assert!( aview1(&[1., 0.]).broadcast((10, 2)).unwrap() == aview2(&[[1., 0.]; 10]) );
pub fn swap_axes(&mut self, ax: usize, bx: usize)
[src]
Swap axes ax
and bx
.
This does not move any data, it just adjusts the array’s dimensions and strides.
Panics if the axes are out of bounds.
use ndarray::arr2; let mut a = arr2(&[[1., 2., 3.]]); a.swap_axes(0, 1); assert!( a == arr2(&[[1.], [2.], [3.]]) );
pub fn t(&self) -> ArrayBase<ViewRepr<&A>, D> where
S: Data,
[src]
S: Data,
Return a transposed view of the array.
This is a shorthand for self.view().reversed_axes()
.
See also the more general methods .reversed_axes()
and .swap_axes()
.
pub fn axes(&self) -> Axes<'_, D>
[src]
Return an iterator over the length and stride of each axis.
pub fn max_stride_axis(&self) -> Axis
[src]
Return the axis with the greatest stride (by absolute value), preferring axes with len > 1.
pub fn invert_axis(&mut self, axis: Axis)
[src]
Reverse the stride of axis
.
Panics if the axis is out of bounds.
pub fn merge_axes(&mut self, take: Axis, into: Axis) -> bool
[src]
If possible, merge in the axis take
to into
.
Returns true
iff the axes are now merged.
This method merges the axes if movement along the two original axes
(moving fastest along the into
axis) can be equivalently represented
as movement along one (merged) axis. Merging the axes preserves this
order in the merged axis. If take
and into
are the same axis, then
the axis is "merged" if its length is ≤ 1.
If the return value is true
, then the following hold:
-
The new length of the
into
axis is the product of the original lengths of the two axes. -
The new length of the
take
axis is 0 if the product of the original lengths of the two axes is 0, and 1 otherwise.
If the return value is false
, then merging is not possible, and the
original shape and strides have been preserved.
Note that the ordering constraint means that if it's possible to merge
take
into into
, it's usually not possible to merge into
into
take
, and vice versa.
use ndarray::Array3; use ndarray::Axis; let mut a = Array3::<f64>::zeros((2, 3, 4)); assert!(a.merge_axes(Axis(1), Axis(2))); assert_eq!(a.shape(), &[2, 1, 12]);
Panics if an axis is out of bounds.
pub fn assign<E, S2>(&mut self, rhs: &ArrayBase<S2, E>) where
A: Clone,
E: Dimension,
S: DataMut,
S2: Data<Elem = A>,
[src]
A: Clone,
E: Dimension,
S: DataMut,
S2: Data<Elem = A>,
Perform an elementwise assigment to self
from rhs
.
If their shapes disagree, rhs
is broadcast to the shape of self
.
Panics if broadcasting isn’t possible.
pub fn fill(&mut self, x: A) where
A: Clone,
S: DataMut,
[src]
A: Clone,
S: DataMut,
Perform an elementwise assigment to self
from element x
.
pub fn zip_mut_with<B, S2, E, F>(&mut self, rhs: &ArrayBase<S2, E>, f: F) where
E: Dimension,
F: FnMut(&mut A, &B),
S: DataMut,
S2: Data<Elem = B>,
[src]
E: Dimension,
F: FnMut(&mut A, &B),
S: DataMut,
S2: Data<Elem = B>,
Traverse two arrays in unspecified order, in lock step,
calling the closure f
on each element pair.
If their shapes disagree, rhs
is broadcast to the shape of self
.
Panics if broadcasting isn’t possible.
pub fn fold<'a, F, B>(&'a self, init: B, f: F) -> B where
A: 'a,
F: FnMut(B, &'a A) -> B,
S: Data,
[src]
A: 'a,
F: FnMut(B, &'a A) -> B,
S: Data,
Traverse the array elements and apply a fold, returning the resulting value.
Elements are visited in arbitrary order.
pub fn map<'a, B, F>(&'a self, f: F) -> ArrayBase<OwnedRepr<B>, D> where
A: 'a,
F: FnMut(&'a A) -> B,
S: Data,
[src]
A: 'a,
F: FnMut(&'a A) -> B,
S: Data,
Call f
by reference on each element and create a new array
with the new values.
Elements are visited in arbitrary order.
Return an array with the same shape as self
.
use ndarray::arr2; let a = arr2(&[[ 0., 1.], [-1., 2.]]); assert!( a.map(|x| *x >= 1.0) == arr2(&[[false, true], [false, true]]) );
pub fn map_mut<'a, B, F>(&'a mut self, f: F) -> ArrayBase<OwnedRepr<B>, D> where
A: 'a,
F: FnMut(&'a mut A) -> B,
S: DataMut,
[src]
A: 'a,
F: FnMut(&'a mut A) -> B,
S: DataMut,
Call f
on a mutable reference of each element and create a new array
with the new values.
Elements are visited in arbitrary order.
Return an array with the same shape as self
.
pub fn mapv<B, F>(&self, f: F) -> ArrayBase<OwnedRepr<B>, D> where
A: Clone,
F: FnMut(A) -> B,
S: Data,
[src]
A: Clone,
F: FnMut(A) -> B,
S: Data,
Call f
by value on each element and create a new array
with the new values.
Elements are visited in arbitrary order.
Return an array with the same shape as self
.
use ndarray::arr2; let a = arr2(&[[ 0., 1.], [-1., 2.]]); assert!( a.mapv(f32::abs) == arr2(&[[0., 1.], [1., 2.]]) );
pub fn map_inplace<F>(&mut self, f: F) where
F: FnMut(&mut A),
S: DataMut,
[src]
F: FnMut(&mut A),
S: DataMut,
Modify the array in place by calling f
by mutable reference on each element.
Elements are visited in arbitrary order.
pub fn mapv_inplace<F>(&mut self, f: F) where
A: Clone,
F: FnMut(A) -> A,
S: DataMut,
[src]
A: Clone,
F: FnMut(A) -> A,
S: DataMut,
Modify the array in place by calling f
by value on each element.
The array is updated with the new values.
Elements are visited in arbitrary order.
use approx::assert_abs_diff_eq; use ndarray::arr2; let mut a = arr2(&[[ 0., 1.], [-1., 2.]]); a.mapv_inplace(f32::exp); assert_abs_diff_eq!( a, arr2(&[[1.00000, 2.71828], [0.36788, 7.38906]]), epsilon = 1e-5, );
pub fn visit<'a, F>(&'a self, f: F) where
A: 'a,
F: FnMut(&'a A),
S: Data,
[src]
A: 'a,
F: FnMut(&'a A),
S: Data,
Visit each element in the array by calling f
by reference
on each element.
Elements are visited in arbitrary order.
pub fn fold_axis<B, F>(
&self,
axis: Axis,
init: B,
fold: F
) -> ArrayBase<OwnedRepr<B>, <D as Dimension>::Smaller> where
B: Clone,
D: RemoveAxis,
F: FnMut(&B, &A) -> B,
S: Data,
[src]
&self,
axis: Axis,
init: B,
fold: F
) -> ArrayBase<OwnedRepr<B>, <D as Dimension>::Smaller> where
B: Clone,
D: RemoveAxis,
F: FnMut(&B, &A) -> B,
S: Data,
Fold along an axis.
Combine the elements of each subview with the previous using the fold
function and initial value init
.
Return the result as an Array
.
Panics if axis
is out of bounds.
pub fn map_axis<'a, B, F>(
&'a self,
axis: Axis,
mapping: F
) -> ArrayBase<OwnedRepr<B>, <D as Dimension>::Smaller> where
A: 'a,
D: RemoveAxis,
F: FnMut(ArrayBase<ViewRepr<&'a A>, Dim<[usize; 1]>>) -> B,
S: Data,
[src]
&'a self,
axis: Axis,
mapping: F
) -> ArrayBase<OwnedRepr<B>, <D as Dimension>::Smaller> where
A: 'a,
D: RemoveAxis,
F: FnMut(ArrayBase<ViewRepr<&'a A>, Dim<[usize; 1]>>) -> B,
S: Data,
Reduce the values along an axis into just one value, producing a new array with one less dimension.
Elements are visited in arbitrary order.
Return the result as an Array
.
Panics if axis
is out of bounds.
pub fn map_axis_mut<'a, B, F>(
&'a mut self,
axis: Axis,
mapping: F
) -> ArrayBase<OwnedRepr<B>, <D as Dimension>::Smaller> where
A: 'a,
D: RemoveAxis,
F: FnMut(ArrayBase<ViewRepr<&'a mut A>, Dim<[usize; 1]>>) -> B,
S: DataMut,
[src]
&'a mut self,
axis: Axis,
mapping: F
) -> ArrayBase<OwnedRepr<B>, <D as Dimension>::Smaller> where
A: 'a,
D: RemoveAxis,
F: FnMut(ArrayBase<ViewRepr<&'a mut A>, Dim<[usize; 1]>>) -> B,
S: DataMut,
Reduce the values along an axis into just one value, producing a new array with one less dimension. 1-dimensional lanes are passed as mutable references to the reducer, allowing for side-effects.
Elements are visited in arbitrary order.
Return the result as an Array
.
Panics if axis
is out of bounds.
pub fn accumulate_axis_inplace<F>(&mut self, axis: Axis, f: F) where
F: FnMut(&A, &mut A),
S: DataMut,
[src]
F: FnMut(&A, &mut A),
S: DataMut,
Iterates over pairs of consecutive elements along the axis.
The first argument to the closure is an element, and the second argument is the next element along the axis. Iteration is guaranteed to proceed in order along the specified axis, but in all other respects the iteration order is unspecified.
Example
For example, this can be used to compute the cumulative sum along an axis:
use ndarray::{array, Axis}; let mut arr = array![ [[1, 2], [3, 4], [5, 6]], [[7, 8], [9, 10], [11, 12]], ]; arr.accumulate_axis_inplace(Axis(1), |&prev, curr| *curr += prev); assert_eq!( arr, array![ [[1, 2], [4, 6], [9, 12]], [[7, 8], [16, 18], [27, 30]], ], );
pub fn to_vec(&self) -> Vec<A> where
A: Clone,
S: Data,
[src]
A: Clone,
S: Data,
Return an vector with the elements of the one-dimensional array.
pub fn row(&self, index: usize) -> ArrayBase<ViewRepr<&A>, Dim<[usize; 1]>> where
S: Data,
[src]
S: Data,
Return an array view of row index
.
Panics if index
is out of bounds.
use ndarray::array; let array = array![[1., 2.], [3., 4.]]; assert_eq!(array.row(0), array![1., 2.]);
pub fn row_mut(
&mut self,
index: usize
) -> ArrayBase<ViewRepr<&mut A>, Dim<[usize; 1]>> where
S: DataMut,
[src]
&mut self,
index: usize
) -> ArrayBase<ViewRepr<&mut A>, Dim<[usize; 1]>> where
S: DataMut,
Return a mutable array view of row index
.
Panics if index
is out of bounds.
use ndarray::array; let mut array = array![[1., 2.], [3., 4.]]; array.row_mut(0)[1] = 5.; assert_eq!(array, array![[1., 5.], [3., 4.]]);
pub fn nrows(&self) -> usize
[src]
Return the number of rows (length of Axis(0)
) in the two-dimensional array.
use ndarray::array; let array = array![[1., 2.], [3., 4.]]; assert_eq!(array.nrows(), 2usize);
pub fn rows(&self) -> usize
[src]
Renamed to .nrows(), please use the new name
Return the number of rows (length of Axis(0)
) in the two-dimensional array.
pub fn column(&self, index: usize) -> ArrayBase<ViewRepr<&A>, Dim<[usize; 1]>> where
S: Data,
[src]
S: Data,
Return an array view of column index
.
Panics if index
is out of bounds.
use ndarray::array; let array = array![[1., 2.], [3., 4.]]; assert_eq!(array.column(0), array![1., 3.]);
pub fn column_mut(
&mut self,
index: usize
) -> ArrayBase<ViewRepr<&mut A>, Dim<[usize; 1]>> where
S: DataMut,
[src]
&mut self,
index: usize
) -> ArrayBase<ViewRepr<&mut A>, Dim<[usize; 1]>> where
S: DataMut,
Return a mutable array view of column index
.
Panics if index
is out of bounds.
use ndarray::array; let mut array = array![[1., 2.], [3., 4.]]; array.column_mut(0)[1] = 5.; assert_eq!(array, array![[1., 2.], [5., 4.]]);
pub fn ncols(&self) -> usize
[src]
Return the number of columns (length of Axis(1)
) in the two-dimensional array.
use ndarray::array; let array = array![[1., 2.], [3., 4.]]; assert_eq!(array.ncols(), 2usize);
pub fn cols(&self) -> usize
[src]
Renamed to .ncols(), please use the new name
Return the number of columns (length of Axis(1)
) in the two-dimensional array.
pub fn is_square(&self) -> bool
[src]
Return true if the array is square, false otherwise.
Examples
Sqaure:
use ndarray::array; let array = array![[1., 2.], [3., 4.]]; assert!(array.is_square());
Not sqaure:
use ndarray::array; let array = array![[1., 2., 5.], [3., 4., 6.]]; assert!(!array.is_square());
pub fn insert_axis_inplace(&mut self, axis: Axis)
[src]
Insert new array axis of length 1 at axis
, modifying the shape and
strides in-place.
Panics if the axis is out of bounds.
use ndarray::{Axis, arr2, arr3}; let mut a = arr2(&[[1, 2, 3], [4, 5, 6]]).into_dyn(); assert_eq!(a.shape(), &[2, 3]); a.insert_axis_inplace(Axis(1)); assert_eq!(a, arr3(&[[[1, 2, 3]], [[4, 5, 6]]]).into_dyn()); assert_eq!(a.shape(), &[2, 1, 3]);
pub fn index_axis_inplace(&mut self, axis: Axis, index: usize)
[src]
Collapses the array to index
along the axis and removes the axis,
modifying the shape and strides in-place.
Panics if axis
or index
is out of bounds.
use ndarray::{Axis, arr1, arr2}; let mut a = arr2(&[[1, 2, 3], [4, 5, 6]]).into_dyn(); assert_eq!(a.shape(), &[2, 3]); a.index_axis_inplace(Axis(1), 1); assert_eq!(a, arr1(&[2, 5]).into_dyn()); assert_eq!(a.shape(), &[2]);
pub fn sum(&self) -> A where
A: Clone + Add<A, Output = A> + Zero,
[src]
A: Clone + Add<A, Output = A> + Zero,
Return the sum of all elements in the array.
use ndarray::arr2; let a = arr2(&[[1., 2.], [3., 4.]]); assert_eq!(a.sum(), 10.);
pub fn mean(&self) -> Option<A> where
A: Clone + FromPrimitive + Add<A, Output = A> + Div<A, Output = A> + Zero,
[src]
A: Clone + FromPrimitive + Add<A, Output = A> + Div<A, Output = A> + Zero,
Returns the arithmetic mean x̅ of all elements in the array:
1 n
x̅ = ― ∑ xᵢ
n i=1
If the array is empty, None
is returned.
Panics if A::from_usize()
fails to convert the number of elements in the array.
pub fn scalar_sum(&self) -> A where
A: Clone + Add<A, Output = A> + Zero,
[src]
A: Clone + Add<A, Output = A> + Zero,
Return the sum of all elements in the array.
This method has been renamed to .sum()
and will be deprecated in the
next version.
pub fn product(&self) -> A where
A: Clone + Mul<A, Output = A> + One,
[src]
A: Clone + Mul<A, Output = A> + One,
Return the product of all elements in the array.
use ndarray::arr2; let a = arr2(&[[1., 2.], [3., 4.]]); assert_eq!(a.product(), 24.);
pub fn sum_axis(
&self,
axis: Axis
) -> ArrayBase<OwnedRepr<A>, <D as Dimension>::Smaller> where
A: Clone + Zero<Output = A> + Add<A>,
D: RemoveAxis,
[src]
&self,
axis: Axis
) -> ArrayBase<OwnedRepr<A>, <D as Dimension>::Smaller> where
A: Clone + Zero<Output = A> + Add<A>,
D: RemoveAxis,
Return sum along axis
.
use ndarray::{aview0, aview1, arr2, Axis}; let a = arr2(&[[1., 2., 3.], [4., 5., 6.]]); assert!( a.sum_axis(Axis(0)) == aview1(&[5., 7., 9.]) && a.sum_axis(Axis(1)) == aview1(&[6., 15.]) && a.sum_axis(Axis(0)).sum_axis(Axis(0)) == aview0(&21.) );
Panics if axis
is out of bounds.
pub fn mean_axis(
&self,
axis: Axis
) -> Option<ArrayBase<OwnedRepr<A>, <D as Dimension>::Smaller>> where
A: Clone + Zero<Output = A> + FromPrimitive + Add<A> + Div<A, Output = A>,
D: RemoveAxis,
[src]
&self,
axis: Axis
) -> Option<ArrayBase<OwnedRepr<A>, <D as Dimension>::Smaller>> where
A: Clone + Zero<Output = A> + FromPrimitive + Add<A> + Div<A, Output = A>,
D: RemoveAxis,
Return mean along axis
.
Return None
if the length of the axis is zero.
Panics if axis
is out of bounds or if A::from_usize()
fails for the axis length.
use ndarray::{aview0, aview1, arr2, Axis}; let a = arr2(&[[1., 2., 3.], [4., 5., 6.]]); assert!( a.mean_axis(Axis(0)).unwrap() == aview1(&[2.5, 3.5, 4.5]) && a.mean_axis(Axis(1)).unwrap() == aview1(&[2., 5.]) && a.mean_axis(Axis(0)).unwrap().mean_axis(Axis(0)).unwrap() == aview0(&3.5) );
pub fn var_axis(
&self,
axis: Axis,
ddof: A
) -> ArrayBase<OwnedRepr<A>, <D as Dimension>::Smaller> where
A: Float + FromPrimitive,
D: RemoveAxis,
[src]
&self,
axis: Axis,
ddof: A
) -> ArrayBase<OwnedRepr<A>, <D as Dimension>::Smaller> where
A: Float + FromPrimitive,
D: RemoveAxis,
Return variance along axis
.
The variance is computed using the Welford one-pass algorithm.
The parameter ddof
specifies the "delta degrees of freedom". For
example, to calculate the population variance, use ddof = 0
, or to
calculate the sample variance, use ddof = 1
.
The variance is defined as:
1 n
variance = ―――――――― ∑ (xᵢ - x̅)²
n - ddof i=1
where
1 n
x̅ = ― ∑ xᵢ
n i=1
and n
is the length of the axis.
Panics if ddof
is less than zero or greater than n
, if axis
is out of bounds, or if A::from_usize()
fails for any any of the
numbers in the range 0..=n
.
Example
use ndarray::{aview1, arr2, Axis}; let a = arr2(&[[1., 2.], [3., 4.], [5., 6.]]); let var = a.var_axis(Axis(0), 1.); assert_eq!(var, aview1(&[4., 4.]));
pub fn std_axis(
&self,
axis: Axis,
ddof: A
) -> ArrayBase<OwnedRepr<A>, <D as Dimension>::Smaller> where
A: Float + FromPrimitive,
D: RemoveAxis,
[src]
&self,
axis: Axis,
ddof: A
) -> ArrayBase<OwnedRepr<A>, <D as Dimension>::Smaller> where
A: Float + FromPrimitive,
D: RemoveAxis,
Return standard deviation along axis
.
The standard deviation is computed from the variance using the Welford one-pass algorithm.
The parameter ddof
specifies the "delta degrees of freedom". For
example, to calculate the population standard deviation, use ddof = 0
,
or to calculate the sample standard deviation, use ddof = 1
.
The standard deviation is defined as:
⎛ 1 n ⎞
stddev = sqrt ⎜ ―――――――― ∑ (xᵢ - x̅)²⎟
⎝ n - ddof i=1 ⎠
where
1 n
x̅ = ― ∑ xᵢ
n i=1
and n
is the length of the axis.
Panics if ddof
is less than zero or greater than n
, if axis
is out of bounds, or if A::from_usize()
fails for any any of the
numbers in the range 0..=n
.
Example
use ndarray::{aview1, arr2, Axis}; let a = arr2(&[[1., 2.], [3., 4.], [5., 6.]]); let stddev = a.std_axis(Axis(0), 1.); assert_eq!(stddev, aview1(&[2., 2.]));
pub fn all_close<S2, E>(&self, rhs: &ArrayBase<S2, E>, tol: A) -> bool where
A: Float,
E: Dimension,
S2: Data<Elem = A>,
[src]
A: Float,
E: Dimension,
S2: Data<Elem = A>,
Use abs_diff_eq
- it requires the approx
crate feature
Return true
if the arrays' elementwise differences are all within
the given absolute tolerance, false
otherwise.
If their shapes disagree, rhs
is broadcast to the shape of self
.
Panics if broadcasting to the same shape isn’t possible.
pub fn dot<Rhs>(
&self,
rhs: &Rhs
) -> <ArrayBase<S, Dim<[usize; 1]>> as Dot<Rhs>>::Output where
ArrayBase<S, Dim<[usize; 1]>>: Dot<Rhs>,
[src]
&self,
rhs: &Rhs
) -> <ArrayBase<S, Dim<[usize; 1]>> as Dot<Rhs>>::Output where
ArrayBase<S, Dim<[usize; 1]>>: Dot<Rhs>,
Perform dot product or matrix multiplication of arrays self
and rhs
.
Rhs
may be either a one-dimensional or a two-dimensional array.
If Rhs
is one-dimensional, then the operation is a vector dot
product, which is the sum of the elementwise products (no conjugation
of complex operands, and thus not their inner product). In this case,
self
and rhs
must be the same length.
If Rhs
is two-dimensional, then the operation is matrix
multiplication, where self
is treated as a row vector. In this case,
if self
is shape M, then rhs
is shape M × N and the result is
shape N.
Panics if the array shapes are incompatible.
Note: If enabled, uses blas dot
for elements of f32, f64
when memory
layout allows.
pub fn dot<Rhs>(
&self,
rhs: &Rhs
) -> <ArrayBase<S, Dim<[usize; 2]>> as Dot<Rhs>>::Output where
ArrayBase<S, Dim<[usize; 2]>>: Dot<Rhs>,
[src]
&self,
rhs: &Rhs
) -> <ArrayBase<S, Dim<[usize; 2]>> as Dot<Rhs>>::Output where
ArrayBase<S, Dim<[usize; 2]>>: Dot<Rhs>,
Perform matrix multiplication of rectangular arrays self
and rhs
.
Rhs
may be either a one-dimensional or a two-dimensional array.
If Rhs is two-dimensional, they array shapes must agree in the way that
if self
is M × N, then rhs
is N × K.
Return a result array with shape M × K.
Panics if shapes are incompatible or the number of elements in the
result would overflow isize
.
Note: If enabled, uses blas gemv/gemm
for elements of f32, f64
when memory layout allows. The default matrixmultiply backend
is otherwise used for f32, f64
for all memory layouts.
use ndarray::arr2; let a = arr2(&[[1., 2.], [0., 1.]]); let b = arr2(&[[1., 2.], [2., 3.]]); assert!( a.dot(&b) == arr2(&[[5., 8.], [2., 3.]]) );
pub fn scaled_add<S2, E>(&mut self, alpha: A, rhs: &ArrayBase<S2, E>) where
A: LinalgScalar,
E: Dimension,
S: DataMut,
S2: Data<Elem = A>,
[src]
A: LinalgScalar,
E: Dimension,
S: DataMut,
S2: Data<Elem = A>,
Perform the operation self += alpha * rhs
efficiently, where
alpha
is a scalar and rhs
is another array. This operation is
also known as axpy
in BLAS.
If their shapes disagree, rhs
is broadcast to the shape of self
.
Panics if broadcasting isn’t possible.
pub fn into_slice(&self) -> Option<&'a [A]>
[src]
into_slice
has been renamed to to_slice
Return the array’s data as a slice, if it is contiguous and in standard order.
Return None
otherwise.
pub fn to_slice(&self) -> Option<&'a [A]>
[src]
Return the array’s data as a slice, if it is contiguous and in standard order.
Return None
otherwise.
pub fn is_view(&self) -> bool
[src]
Returns true
iff the array is the view (borrowed) variant.
pub fn is_owned(&self) -> bool
[src]
Returns true
iff the array is the owned variant.
Trait Implementations
impl<T> Clone for Array2<T> where
T: Clone,
T: Clone,
pub fn clone(&self) -> Array2<T>
fn clone_from(&mut self, source: &Self)
1.0.0[src]
impl<T> Debug for Array2<T> where
T: Debug,
T: Debug,
impl<T> Deref for Array2<T>
type Target = ArrayBase<OwnedRepr<T>, Dim<[usize; 2]>>
The resulting type after dereferencing.
pub fn deref(&self) -> &ArrayBase<OwnedRepr<T>, Dim<[usize; 2]>>
impl<T> DerefMut for Array2<T>
impl<T> Index<(usize, usize)> for Array2<T>
impl<T> IndexMut<(usize, usize)> for Array2<T>
impl<T> PartialEq<Array2<T>> for Array2<T> where
T: PartialEq<T>,
T: PartialEq<T>,
impl<T> StructuralPartialEq for Array2<T>
Auto Trait Implementations
impl<T> RefUnwindSafe for Array2<T> where
T: RefUnwindSafe,
T: RefUnwindSafe,
impl<T> Send for Array2<T> where
T: Send,
T: Send,
impl<T> Sync for Array2<T> where
T: Sync,
T: Sync,
impl<T> Unpin for Array2<T>
impl<T> UnwindSafe for Array2<T> where
T: RefUnwindSafe,
T: RefUnwindSafe,
Blanket Implementations
impl<T> Any for T where
T: 'static + ?Sized,
[src]
T: 'static + ?Sized,
impl<T> Borrow<T> for T where
T: ?Sized,
[src]
T: ?Sized,
impl<T> BorrowMut<T> for T where
T: ?Sized,
[src]
T: ?Sized,
pub fn borrow_mut(&mut self) -> &mut T
[src]
impl<T> From<T> for T
[src]
impl<T, U> Into<U> for T where
U: From<T>,
[src]
U: From<T>,
impl<T> Pointable for T
pub const ALIGN: usize
type Init = T
The type for initializers.
pub unsafe fn init(init: <T as Pointable>::Init) -> usize
pub unsafe fn deref<'a>(ptr: usize) -> &'a T
pub unsafe fn deref_mut<'a>(ptr: usize) -> &'a mut T
pub unsafe fn drop(ptr: usize)
impl<T> ToOwned for T where
T: Clone,
[src]
T: Clone,
type Owned = T
The resulting type after obtaining ownership.
pub fn to_owned(&self) -> T
[src]
pub fn clone_into(&self, target: &mut T)
[src]
impl<T, U> TryFrom<U> for T where
U: Into<T>,
[src]
U: Into<T>,
type Error = Infallible
The type returned in the event of a conversion error.
pub fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>
[src]
impl<T, U> TryInto<U> for T where
U: TryFrom<T>,
[src]
U: TryFrom<T>,
type Error = <U as TryFrom<T>>::Error
The type returned in the event of a conversion error.
pub fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>
[src]
impl<V, T> VZip<V> for T where
V: MultiLane<T>,
V: MultiLane<T>,