I have a 2d vec and I wanted to get the nth element in all the nested vec. Below is my code,
pub fn main() {
let vec_2d: Vec<Vec<f32>> = vec![vec![0f32; 10]; 3];
let sub_vec: Vec<f32> = vec_2d[..][0].clone();
println!("{:?}", vec_2d);
println!("{:?}", sub_vec); // expected a vec [0,0,0]
}
I thought when I mentioned [..] it will take the 3 elements and [0] picks the first element in those. Is there any simple way of collecting the nth element in a 2d vec? I expected a similar syntax to matlab arr2[:,1]
Note: My actual code contains struct and not f32 and I am not using ndarray crate
The vec[..] operation turns an Vec<T> into a slice &[T], so in this case where T = Vec<f32>, you get a slice of &[Vec<f32>]. It doesn't do a transpose as you seem to expect, and if you keep slicing, it's the same as just not using [..] at all.
There's no inbuilt way to do that with vectors, but you can do it with iterators:
pub fn main() {
let vec_2d: Vec<Vec<f32>> = vec![vec![0f32; 10]; 3];
let sub_vec: Vec<f32> = vec_2d.iter().map(|v| v[0]).collect();
println!("{:?}", vec_2d);
println!("{:?}", sub_vec); // expected a vec [0,0,0]
}