Search code examples
multidimensional-arrayviewrustcloneslice

How to efficiently clone a Rust ndarray from a view?


I've created a 1D row view of a 2D ndarray and I'd like to clone the contents. Currently, I'm doing it like this:

let mut row_orig = table.subview_mut(Axis(0), chosen_row);
// ...
// some operations on row_orig
// ...
let mut row_copy = Array1<f32>::zeros(table.cols());
row_copy.assign(&row_orig);  

It seems slightly inefficient to create and initialize with zeros and then perform the copy. Plus, I have to declare row_copy as mutable when it doesn't need to be. Is there a better way? Apparently, .clone doesn't exist for ndarray views.

I thought that using a slice might be the solution, but I'm running into a mutable/immutable problem with this code:

let row_copy = table.slice(s![chosen_row,..]).clone();
// do something mutable with table

Solution

  • I'd like to clone the contents.

    If that is the case, then you do not want just to clone the array view (which would have been just a shallow copy). You want a uniquely owned array with the same contents as another array. That can be done with to_owned.

    let row_orig = table.subview(Axis(0), chosen_row);
    let row_copy = row_orig.to_owned();