[ndarray] in place operations

Hi,

I am new to Rust. Interested in using it to manipulate some large volumetric arrays. I am trying to do an in-place operation on a subset of the array. Note I am not necessarily looking for a crate to do convolution, I would just like to understand more about rust and ndarray crate and whether it is possible to do what I am trying to do in place.

I have an 5x5 array "a" - take a 3x3 subset/slice "w" and multiply that by a kernel "k". When I modify the slice "w" by hand it does the expected and updates the referenced array a. But I cannot figure out how I can formulate an array multiplication with ndarray that will modify a in place. I don't want to copy the result from b back into a.

extern crate ndarray;

use ndarray::prelude::*;

fn main() {
    
    let mut a = Array::<f64, _>::ones((5, 5));
    
    let k = arr2(&[[1.0, 1.0, 1.0], 
                 [2.0, 2.0, 2.0],
                 [3.0, 3.0, 3.0]]);
                 
    let mut w = a.slice_mut(s![0..3, 0..3]);
    
    w[[0, 0]] *= 2.0;
    
    let b = &k * &w;
    
    println!("b: {:?}", b);
    println!("k: {:?}", k);
    println!("a: {:?}", a);
}

(Playground)

Output:

b: [[2.0, 1.0, 1.0],
 [2.0, 2.0, 2.0],
 [3.0, 3.0, 3.0]], shape=[3, 3], strides=[3, 1], layout=Cc (0x5), const ndim=2
k: [[1.0, 1.0, 1.0],
 [2.0, 2.0, 2.0],
 [3.0, 3.0, 3.0]], shape=[3, 3], strides=[3, 1], layout=Cc (0x5), const ndim=2
a: [[2.0, 1.0, 1.0, 1.0, 1.0],
 [1.0, 1.0, 1.0, 1.0, 1.0],
 [1.0, 1.0, 1.0, 1.0, 1.0],
 [1.0, 1.0, 1.0, 1.0, 1.0],
 [1.0, 1.0, 1.0, 1.0, 1.0]], shape=[5, 5], strides=[5, 1], layout=Cc (0x5), const ndim=2

Errors:

   Compiling playground v0.0.1 (/playground)
    Finished dev [unoptimized + debuginfo] target(s) in 2.43s
     Running `target/debug/playground`

Are you just looking for w *= &k? (Per-element multiplication.)

1 Like

Oh thats embarressing - I thought I had tried that but I just replaced let b = &k * &w; with w *= &k; and it does exactly what I was after. Thanks:

Solution for in-place array multiplication