How to convert a vector if Arrays into an Array along a new dimension? #1150
-
| Suppose that we have a vector of 5 Arrays. Also let the shapes of theses Arrays be uniform and known, say (3, 3). let a: Vec<Array2<f64>> = vec![ # five Arrays ];Do we have any constructor method to create a new Array of shape (5, 3, 3) from this vector? | 
Beta Was this translation helpful? Give feedback.
      
      
          Answered by
          
            jturner314
          
      
      
        Jan 22, 2022 
      
    
    Replies: 1 comment 2 replies
-
| 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(())
} | 
Beta Was this translation helpful? Give feedback.
                  
                    2 replies
                  
                
            
      Answer selected by
        zgbkdlm
  
    Sign up for free
    to join this conversation on GitHub.
    Already have an account?
    Sign in to comment
  
        
    
This is an area which could be improved. There are a couple of ways to do this using existing functionality:
(Playg…