Using an NDArray from a function (can't index into ArrayBase)

I'm having a little trouble trying to use an ndarray from within a function. This program:

use ndarray::prelude::*;

fn main() {
    let mut a: Array::<f64,_> = array![
                [1.,2.,3.], 
                [4.,5.,6.],
                [7.,8.,9.],
            ]; 

    print_and_zero(&mut a);
    println!("{}",a[[0,0]]); //this works
}

fn print_and_zero<T>(arr: &mut Array::<f64,T>) {

    println!("{}",arr[[0,0]]); //this doesnt compile
    arr[[0,0]] = 0.0;
}

...fails with a compiler error:

error[E0608]: cannot index into a value of type `&mut ArrayBase<OwnedRepr<f64>, T>`
  --> src/main.rs:16:19
   |
16 |     println!("{}",arr[[0,0]]); //this doesnt compile
   |                   ^^^^^^^^^^

error[E0608]: cannot index into a value of type `&mut ArrayBase<OwnedRepr<f64>, T>`
  --> src/main.rs:17:5
   |
17 |     arr[[0,0]] = 0.0;
   |     ^^^^^^^^^^

...whereas another program using only Rust arrays, works fine. Undoubtedly I'm missing something easy about how to pass an ndarray to a function.

Thanks!

What you can index by depends on the dimension of the Array -- the second type parameter. But your function is generic over that parameter. You could indicate the functionality you're trying to use:

fn print_and_zero<T>(arr: &mut Array::<f64,T>)
where
    Array::<f64, T>: Index<[usize; 2], Output=f64> + IndexMut<[usize; 2]>,

But probably you just want to not be generic here:

fn print_and_zero(arr: &mut Array::<f64,Dim<[usize; 2]>>) {
2 Likes

That did the trick. Thanks!

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.