0

I have a struct with an array

struct Model<const D: usize> {
  b: f64,
  j: f64,
  arr: Array<f64, Dim<[Ix, D]>,
}

And I noticed that I cannot access the value in arr via [usize; D], e.g.

impl<const D: usize> for Model<D> {
  fn sum(&self) -> f64 {
    // ...
    let mut cursor = [0; D];
    sum += arr[[cursor]]; // fail with error 
  }
}

because cursor is not implementing corresponding traits:

the trait bound [i32; D]: NdIndex<ndarray::Dim<[usize; D]>> is not satisfied

I would expect for an arbitrary D > 0 ndarray should be able to handle it. Yet it is not possible. I am wondering if there is a workaround for this kind of isssue.

xis
  • 24,330
  • 9
  • 43
  • 59
  • Did you try `let mut cursor = [0 as usize; D]`? `i32` is not `usize`, but I'm not sure if that's the problem. – Thomas Oct 27 '22 at 17:57
  • @Thomas unfortunately no, the error is "the trait `NdIndex>` is not implemented for `[usize; D]`" – xis Oct 27 '22 at 18:16
  • `NdIndex` [is only implemented](https://docs.rs/ndarray/latest/ndarray/trait.NdIndex.html) up to `[usize; 6]`, but it's also implemented for `[usize]` slices, so `arr[&cursor]` might work. – Thomas Oct 27 '22 at 18:19
  • @Thomas -- unfortunately not. Error is "required because of the requirements on the impl of `std::ops::Index<&[usize]>` for `ArrayBase, ndarray::Dim<[usize; D]>>`", while I am using `model[&s[..]]` where `s = [0 as usize; D]` – xis Oct 27 '22 at 19:46
  • I tried your code but it gives several other compilation errors. After fixing those with _guesses_ at what your _actual_ code looked like, I got a different error than what you posted: `cannot index into a value of type ArrayBase, Dim<[usize; D]>>`. So please provide a minimal, self-contained, compilable example that demonstrates the error you're getting. – Thomas Oct 28 '22 at 07:49

0 Answers0