在 Rust 的 Ndarray crate 中,roll() 有什么替代方法?

4
在Numpy中有一个名为roll的函数,但ndarray文档中没有提到类似的内容。
我正在尝试用整数“滚动”我的数组。例如:
let ar = arr2(&[[1.,2.,3.], [7., 8., 9.]]);

调用numpy的roll(ar, 1)函数将产生所需的结果:

[[3.,1., 2.],
 [9., 7., 8.]]

在 Rust 中是否有 ndarray 的替代品或解决方法?

更新:发现这个旧的开放线程,不确定是否已经实现了更为最新的解决方案:https://github.com/rust-ndarray/ndarray/issues/281

1个回答

1
Ndarray文档提供了一个示例: https://docs.rs/ndarray/latest/ndarray/struct.ArrayBase.html#method.uninit 然而,它没有给出预期的结果。我稍作修改:
/// Shifts 2D array by {int} to the right
/// Creates a new Array2 (cloning)
fn shift_right_by(by: usize, a: &Array2<f64>) -> Array2<f64> {
    // if shift_by is > than number of columns
    let x: isize = (by % a.len_of(Axis(1))) as isize;

    // if shift by 0 simply return the original
    if x == 0 {
        return a.clone();
    }
    // create an uninitialized array
    let mut b = Array2::uninit(a.dim());

    // x first columns in b are two last in a
    // rest of columns in b are the initial columns in a
    a.slice(s![.., -x..]).assign_to(b.slice_mut(s![.., ..x]));
    a.slice(s![.., ..-x]).assign_to(b.slice_mut(s![.., x..]));

    // Now we can promise that `b` is safe to use with all operations
    unsafe { b.assume_init() }
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接