How to get a nth element of all nested vec in a vec

Hi All,

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]
}
1 Like

You can enjoy simpler syntax if you are able to use the ndarray crate:

use ndarray::prelude::*;

fn main() {
    let matrix: Array2<f32> = Array::zeros([3, 10]);
    let column = matrix.index_axis(Axis(1), 1);

    let vec: Vec<_> = column.iter().collect();
    println!("{:?}", vec); // [0.0, 0.0, 0.0]
}

(playground)

The index_axis method is used here. index_axis(Axis(1), 1) gets the second subarray along the second axis.

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.