Dak
Dak

Reputation: 31

How to convert a Vec to a ndarray

I'm starting to learn rust, so let me know if there is a more proper way I should be approaching this problem, but I'm looking for similar performance of numpy from python when doing element wise operations on vectors. It looks like the ndarray crate is a good fit, but I'm having a hard time turning a Vec into a ndarray. Starting with:

let mut A:Vec<f32> = vec![];

How would I do something like:

let B = array!(A);

after filling in the vector?

I didn't see a way to cast the vector to an ndarray like I would in python with lists. Do I really have to just use a for loop and set each index individually to an empty ndarray?

Upvotes: 0

Views: 2425

Answers (2)

DrStrangeLove
DrStrangeLove

Reputation: 152

You can use from_vec to create an ndarray from a vector or from_shape_vec to create a vector of a custom dimension.

// You can use from_vec
let one_dim_vector = Array::from_vec(vec![1, 2, 3, 4]);
println!("Vector created from_vec:\n{:#?}", one_dim_vector);

Or you can create it from an iterable:

let one_dim_vector_from_iterable = Array::from_iter(1..5);
println!(
    "Vector created from_iter:\n{:#?}",
    one_dim_vector_from_iterable
);

You can also create it for a custom dimension passing a tuple of (rows, columns):

let vector_of_custom_dimension = Array::from_shape_vec((3, 2), vec![1., 2., 3., 4., 5., 6.]);
match vector_of_custom_dimension {
    Ok(vector) => println!("Vector created from_shape_vec:\n{:#?}", vector),
    Err(error) => println!("Error: {:#?}", error),
}

This will output:

Vector created from_vec: [1, 2, 3, 4]
Vector created from_iter: [1, 2, 3, 4]
Vector created from_shape_vec: 
[[1.0, 2.0],
 [3.0, 4.0]], 

Upvotes: 2

Chayim Friedman
Chayim Friedman

Reputation: 71075

ArrayBase implements From<Vec>, so you can just use that:

let B = ndarray::Array1::from(A);

Upvotes: 2

Related Questions