如何从另一个 Array2 获得零 Array2 复制维度

How to get a zero Array2 copying dimension from another Array2

刚刚学习一些 Rust。我正在使用 ndarray 并且我需要构建一个零矩阵来复制另一个矩阵的维度。我试过了

fn make_0(matrix: Array2<i32>) -> Array2<i32> {
        Array2::zeros(matrix.shape())
}

但这不能编译:

error[E0271]: type mismatch resolving `<&[usize] as ShapeBuilder>::Dim == Dim<[usize; 2]>`
   --> src/lib.rs:62:9
    |
62  |         Array2::zeros(matrix.shape())
    |         ^^^^^^^^^^^^^ expected array `[usize; 2]`, found struct `IxDynImpl`
    |
    = note: expected struct `Dim<[usize; 2]>`
               found struct `Dim<IxDynImpl>`

我可以用

解决
fn make_0(matrix: Array2<i32>) -> Array2<i32> {
        Array2::zeros((matrix.shape()[0], matrix.shape()[1]))
}

但我想还有更好的东西,我对这里的类型感到困惑。

documentation for ArrayBase::shape() 建议改用 .raw_dim()

Note that you probably don’t want to use this to create an array of the same shape as another array because creating an array with e.g. Array::zeros() using a shape of type &[usize] results in a dynamic-dimensional array. If you want to create an array that has the same shape and dimensionality as another array, use .raw_dim() instead:

// To get the same dimension type, use `.raw_dim()` instead:
let c = Array::zeros(a.raw_dim());
assert_eq!(a, c);

所以你可能想做这样的事情:

fn make_0(matrix: Array2<i32>) -> Array2<i32> {
    Array2::zeros(matrix.raw_dim())
}