【问题标题】:What's alternative for roll() in rust Ndarray crate?rust Ndarray crate 中 roll() 的替代方法是什么?
【发布时间】:2022-12-29 19:49:48
【问题描述】:

Numpy 中有一个roll 函数。但是 ndarray 文档没有提到任何类似的东西。

我正在尝试按整数“滚动”我的数组。例如

let ar = arr2(&[[1.,2.,3.], [7., 8., 9.]]);

调用 numpy roll(ar, 1) 会产生预期的结果:

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

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

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

【问题讨论】:

    标签: multidimensional-array rust rust-ndarray


    【解决方案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() }
    }
    

    【讨论】:

      猜你喜欢
      • 2019-07-20
      • 1970-01-01
      • 1970-01-01
      • 2022-11-13
      • 2015-01-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多