Skip to content

How to convert a vector if Arrays into an Array along a new dimension? #1150

Answered by jturner314
zgbkdlm asked this question in Q&A
Discussion options

You must be logged in to vote

This is an area which could be improved. There are a couple of ways to do this using existing functionality:

use ndarray::prelude::*;

fn main() -> Result<(), Box<dyn std::error::Error>> {
    let owned: Vec<Array2<f64>> = vec![Array2::zeros([3, 3]), Array2::ones([3, 3])];
    
    // Option 1:
    let views: Vec<ArrayView2<'_, f64>> = owned.iter().map(|arr| arr.view()).collect();
    let stacked = ndarray::stack(Axis(0), &views)?;
    println!("Option 1:\n{stacked}\n");
    
    // Option 2:
    let mut stacked: Array3<f64> = Array3::zeros([0, 3, 3]);
    for arr in &owned {
        stacked.push(Axis(0), arr.view())?;
    }
    println!("Option 2:\n{stacked}\n");
    
    Ok(())
}

(Playg…

Replies: 1 comment 2 replies

Comment options

You must be logged in to vote
2 replies
@marstaik
Comment options

@nilgoyette
Comment options

Answer selected by zgbkdlm
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Category
Q&A
Labels
None yet
4 participants