1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
| // you know ahead-of-time the shape of the Array
let mut arr = Array2::zeros((2, 3));
for (i, mut row) in arr.axis_iter_mut(Axis(0)).enumerate() {
// Perform calculations and assign to `row`; this is a trivial example:
row.fill(i);
}
assert_eq!(arr, array![[0, 0, 0], [1, 1, 1]]);
// you don't know ahead-of-time the shape of the Array
// append data to a flat Vec, then conert it using ::from_shape_vec()
let ncols = 3;
let mut data = Vec::new();
let mut nrows = 0;
let arr = Array2::from_shape_vec((nrows, ncols), data)?;
// If neither of these options works for you
// using Iterator::flatten() then ::from_shape_vec()
let nested: Vec<Array2<i32>> = vec![
array![[1, 2, 3], [4, 5, 6]],
array![[7, 8, 9], [10, 11, 12]],
];
let inner_shape = nested[0].dim();
let shape = (nested.len(), inner_shape.0, inner_shape.1);
let flat: Vec<i32> = nested.iter().flatten().cloned().collect();
let arr = Array3::from_shape_vec(shape, flat)?;
assert_eq!(arr, array![
[[1, 2, 3], [4, 5, 6]],
[[7, 8, 9], [10, 11, 12]],
]);
|