rust-ndarray / ndarray

ndarray: an N-dimensional array with array views, multidimensional slicing, and efficient operations
https://docs.rs/ndarray/
Apache License 2.0
3.53k stars 297 forks source link

Inserting 2D array into 4D array. #1270

Closed abishekatp closed 1 year ago

abishekatp commented 1 year ago

How can I insert some 2D array into 4D array. For examples in python numpy we can do that like this

kernels_gradient[i, j] = signal.correlate2d(self.input[j], output_gradient[i], "valid")

In Rust I have a situration

let d4_arr: Array4<f64> = Array4::zeros((2,2,3,2));
let d2_arr: Array2<f64> = Array2::eye((3,2));
// below line is currently not working
d4_arr[[0,0]] = d2_arr;
jturner314 commented 1 year ago

Unfortunately, std::ops::Index and std::ops::IndexMut are somewhat limited, so indexing can only be used to get a single element. To get a slice (i.e. a view) of a portion of an array, you have to use separate slicing methods. See the Slicing overview in the docs. Then, you can call .assign() to assign to that view. Here's an example:

use ndarray::prelude::*;

fn main() {
    let mut d4_arr: Array4<f64> = Array4::zeros((2,2,3,2));

    // eye can only be used for square arrays, so we instead create an array of
    // zeros and then fill the diagonal with ones.
    let mut d2_arr: Array2<f64> = Array2::zeros((3,2));
    d2_arr.diag_mut().fill(1.);

    // Slice to get a portion of the array, then .assign().
    d4_arr.slice_mut(s![0, 0, .., ..]).assign(&d2_arr);

    println!("{}", d4_arr);
}

(Playground)

Since you're coming from NumPy, you may also be interested in the ndarray for NumPy users page.

abishekatp commented 1 year ago

@jturner314 Thank you for the answer. This will work for me. Also the NumPy users page is very useful. I am closing this issue.