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)
请参阅文档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)