如何使用 ndarray 从向量向量创建二维数组?

xos*_*xos 5 arrays multidimensional-array rust

我正在尝试使用ndarray板条箱进行一些生物信息学,但我似乎无法动态创建矩阵。

我有布尔向量,我想将它们组合成一个二维数组。然而,尝试展平向量并使用并into_shape不能保留元素的正确顺序。

因此,我尝试创建一个空数组并将行连接到其中,但这给了我一个我无法理解的错误。我知道空数组没有相同的维度,但我找不到将空数组转换为正确的类型和维度的方法。

use ndarray::{concatenate, Array, Axis, Ix2};

fn main() {
    #[rustfmt::skip]
    let vector_of_vectors = vec![
        vec![true, false, true],
        vec![false, true, false],
    ];

    let mut matrix: Array<bool, Ix2> = ndarray::array![];
    for array in vector_of_vectors.iter() {
        matrix = concatenate![Axis(0), matrix, Array::from(array.clone())];
    }
}
Run Code Online (Sandbox Code Playgroud)
error[E0308]: mismatched types
  --> src/main.rs:12:18
   |
12 |         matrix = concatenate![Axis(0), matrix, Array::from(array.clone())];
   |                  ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ expected an array with a fixed size of 2 elements, found one with 1 element
   |
   = note: expected struct `ArrayBase<ViewRepr<&bool>, Dim<[usize; 2]>>`
              found struct `ArrayBase<ViewRepr<&bool>, Dim<[usize; 1]>>`
   = note: this error originates in a macro (in Nightly builds, run with -Z macro-backtrace for more info)
Run Code Online (Sandbox Code Playgroud)

Jas*_*son 5

请参阅文档ndarray

已知行和列的长度

use ndarray::{Array2, Axis};

fn main() {
    #[rustfmt::skip]
    let rand_vec = vec![
        vec![true, false, true],
        vec![false, true, false],
    ];

    let mut arr = Array2::<bool>::default((2, 3));
    for (i, mut row) in arr.axis_iter_mut(Axis(0)).enumerate() {
        for (j, col) in row.iter_mut().enumerate() {
            *col = rand_vec[i][j];
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

操场

行和列长度未知

该文档建议有效地扁平化Vec使用extend_from_slice并将扁平化结果传递给Array2::from_shape_vec

use ndarray::Array2;

fn main() {
    // A Vec<Vec<bool>> with a random length of rows and columns
    let rand_vec = gen_rand_vec();

    let mut data = Vec::new();

    let ncols = rand_vec.first().map_or(0, |row| row.len());
    let mut nrows = 0;

    for i in 0..rand_vec.len() {
        data.extend_from_slice(&rand_vec[i]);
        nrows += 1;
    }

    let arr = Array2::from_shape_vec((nrows, ncols), data).unwrap();
}
Run Code Online (Sandbox Code Playgroud)

操场

鉴于 的前一个输入rand_vec,两个示例都会为您提供:

[
  [true, false, true],
  [false, true, false],
]
Run Code Online (Sandbox Code Playgroud)

  • 我仍然无法使用“from_shape_vec”从动态大小的数据按列创建矩阵,但似乎有一个通过添加“try_append_row”和“try_append_column”来拉取请求` 二维数组的方法 [https://github.com/rust-ndarray/ndarray/pull/932](https://github.com/rust-ndarray/ndarray/pull/932)。所以这会在未来增加一些人体工程学! (2认同)