How to convert 3D `vec` into a 3D ndarray?

for example, I have a 3D vectors which looks like to be created as below:

vec![vec![vec![3,23,], vec![3,4,]], vec![vec![32,4,], vec![32,4]]];

I know I can create a 3D ndarray by ndarray::arr3(&[[[1,2], [3,4]], [[5, 6], [7, 8]]]) and now I should try create it from 3D vector.

Nested Vecs are often undesirable in the first place, how did you end up creating those and can that perhaps be avoided? The downsides of nested Vecs include

  • worse performance, as there’s multiple steps of indirection, and many smaller independent allocations / memory locations involved
  • worse type safety, as there’s no static enforcement of the structure being regularly shaped, i.e. with a Vec<Vec<Vec<T>>>, the inner vectors and the inner inner vectors could all have inconsistent/different lengths
  • the corner case of size 0 in the first or second dimension leaves sizes in subsequent dimensions unspecified
1 Like

I get the 3D vector by a 3D ndarray which is used a 'map' to get new data and for each map I should collect as vec; then at last I collect a 3D vec. The code is as below:

d3_ndarray.axis_iter(Axis(0)).map(|d2| {
        d2.windows((2, 10))
            .into_iter()
            .map(|d2i| {
                let base_p = d2i.column(4).mean().unwrap();
                let pi = d2i.column(4).map(|x| x / base_p).to_vec();
                vec![*d2i.column(0).first().unwrap()]
                    .into_iter()
                    .chain(pi.into_iter()))
                    .collect::<Vec<_>>()
            })
            .collect::<Vec<_>>()
    }).collect::<Vec<_>>();

This gives me

thread 'main' panicked at 'collapse_axis: Index 4 must be less than axis length 3 for array with shape [2, 3]'

I am sorry for that; in the fact, d2.windows((2,3)) should be d2.windows((2,15)); or column(4) should be column(1).

So, well… some way to solve this it to create a flat Vec with all the values somehow, e.g. by flattening the nested vec you have, or by trying to avoid creating that one in the first place, though when I tried that I’ve run into some borrowing issues from the Windows iterator not accepting any owned parameters, but only &self.

And then you need to figure out the shape of the output and can use something like ::from_shape_vec to create your ndarray type. Figuring out the shape can either happen by carefully calculating it correctly, or perhaps by inspecting the nested vec of vecs.

Here’s some example code Rust Playground

Thank you steffahn for your time and your tries;
All your replies help me much.