rustrust-ndarray

Assign values from a slice of a rust ndarray to an equivalent slice of another ndarray


In Python, say I have two 4D NumPy arrays (the exact number number of dimensions doesn't matter too much other than it being multi-dimensional):

import numpy as np

a = np.ones((4, 5, 6, 7))
b = np.zeros((4, 5, 6, 7))

If I want to assign a certain slice from b into a, I could do, e.g.,:

a[1:3, 0:2, 1::2, :] = b[1:3, 0:2, 1::2, :]

If I have two 4D rust ndarray's, e.g.,

use ndarray::prelude::*

fn main() {
  let mut a = Array4::<f64>::ones((4, 5, 6, 7));
  let b = Array4::<f64>::zeros((4, 5, 6, 7));
}

how would I go about doing an equivalent assignment of a slice of b into a?

This is rather similar, but (I think) not quite the same as:

and there is information in this Github thread.


Solution

  • The way I have found to do this is using the slice_mut method, the assign method and the s! slice macro. For an exact match of the case above, we could do:

    use ndarray::prelude::*;
    
    fn main() {
        let mut a = Array4::<f64>::ones((4, 5, 6, 7));
        let b = Array4::<f64>::zeros((4, 5, 6, 7));
    
        // assign a slice of b into an equivalent slice of a
        a.slice_mut(s![1..3, 0..2, 1..;2, ..]).assign(
            &b.slice(s![1..3, 0..2, 1..;2, ..])
        );
    }