multidimensional-array - 有没有一种好方法可以在使用rust 的 ndarray 中进行重叠复制?

标签 multidimensional-array rust copy borrowing nalgebra

这是我尝试过的

use ndarray::{arr2, s};
let mut a = arr2(&[[1, 2, 3],
                   [4, 5, 6]]);
let b = arr2(&[[2, 3, 3],
               [5, 6, 6]]);

a.slice_mut(s![.., ..2]).assign(&a.slice_mut(s![.., 1..]));

由于借用规则(playround link),这显然失败了:

error[E0499]: cannot borrow `a` as mutable more than once at a time
  --> src/main.rs:13:38
   |
13 |     a.slice_mut(s![.., ..2]).assign(&a.slice_mut(s![.., 1..]));
   |     -                        ------  ^ second mutable borrow occurs here
   |     |                        |
   |     |                        first borrow later used by call
   |     first mutable borrow occurs here

a 是我拥有的,b 是我想要得到的。

在 numpy 中它就像 a[:, :2] = a[:, 1:] 一样简单。

PS 也许nalgebra crate 中有一个简单的解决方案?

最佳答案

在 ndarray 的 master 分支中有一个特殊的宏,比 split_at_mut() 更方便,因为它支持任意切片 - 但当切片重叠时它会崩溃:

use ndarray::multislice;
use ndarray::prelude::*;
let mut arr: Array1<_> = (0..4).collect();
let (mut a, mut b) = multislice!(arr, mut [..;2], mut [1..;2]);
a.assign(&b);

给出 [1,1,3,3]

他们甚至解出一个丢番图方程来验证它。它发生在运行时,而不是编译时 split_at_mut

关于multidimensional-array - 有没有一种好方法可以在使用rust 的 ndarray 中进行重叠复制?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57717133/

相关文章:

c++ - memcpy 和二维数组

python - 获取 numpy ndarray 的一部分(对于任意维度)

rust - gfx-rs/wgpu wgsl 示例使用 @ 而不是 [[]]

rust - 为什么 iter 在模式保护中使用时可变借用?

powershell - 使用Powershell使用变量将文件从一个位置复制到多个位置

java - 打印 3D 数组转换为 2D

c++ - 警告 : ISO C++ forbids variable length array

rust - 获取 Rc 后面对象的引用

xcode - 操作无法完成,因为发生了意外错误(错误代码 -8058)

elasticsearch - Elasticsearch copy_to 字段未填充