How to take a slice of a Rust ndarray with a dynamic shape?

Viewed 557

I'd like to slice a tensor (multi-dimensional array) using Rust's ndarray library, but the catch is that the tensor is dynamically shaped and the slice is stored in a user provided variable.

If I knew the dimensionality up front, I expect I could simply do the following, where idx is the user provided index and x is a 4 dimensional tensor:

// should give a 1D tensor as a view on the last axis at index `idx`
x.slice(s![idx[0], idx[1], idx[2], ..])  

BUT because I don't know the dimensionality up front, I cant manually unpack idx that way and feed it to the slice macro s!.

In python I might do it this way, where idx was a user provided tuple:

# if `len(idx)` was 2 but `x.ndim` was 3, we could get a 1d tensor, of length `x.shape[-1]`
x[idx]  

Whats the proper way to do this in Rust? The ndarray for numpy users only shows how to do it with scalar values given to s!

2 Answers

The documentation for the s! macro says:

Slice argument constructor.

s![] takes a list of ranges/slices/indices, separated by comma, with optional step sizes that are separated from the range by a semicolon. It is converted into a &SliceInfo instance.

It seems you should be able to manually create a SliceInfo object yourself, via SliceInfo::new(idx) (note that idx must be a slice, not a tuple).

Related