How shall I stack a matrix

I want to reshape a 2D matrix into a 3D matrix and then stack on this 3D matrix; I have tried to do this as below code:

let multi_num = 2;
let kline_re = ndarray::arr2(&[[1,2], [3, 4], [5, 6], [7, 8], [9, 10], [11, 12]]);
let kd_shape = kline_re.shape();
let kline_re_3 = kline_re.to_shape(((kline_re.shape()[0] / multi_num, multi_num, kd_shape[1]), Order::RowMajor)).unwrap();
let mut kline_re_splits = vec![];
for i in 0..kline_re_3.shape()[0] {
    kline_re_splits.push(kline_re_3.slice(ndarray::s![i, .., ..]));
let x = ndarray::stack(Axis(1), &kline_re_splits).unwrap();
println!("{:#?}", x);

the final result looks like this:

[[[1, 2],
  [5, 6],
  [9, 10]],

 [[3, 4],
  [7, 8],
  [11, 12]]], shape=[2, 3, 2], strides=[2, 4, 1], layout=c (0x4), const ndim=3

but I don't know how to convert it into a Vec and I think above code is too fussy(I mean maybe there should be more elegant method). so it is really appreciated for any advice.

This is basically reshaping and transposition only:

let rest = x.len() / (3 * 2);
let mut y = x.into_shape([3, 2, rest])?;
y.swap_axes(0, 1);

conversion to Vec is similarly trivial:

let v: Vec<_> = y.into_iter().collect();


Hi H2CO3, thanks for your reply and your code works well except the last line let v: Vec<_> = y.into_iter().collect(); which output is as below:


I know what the result is, obviously – I wrote and checked it myself. What's wrong with that output? It simply collects all the elements into a Vec in the correct order of iteration. You didn't specify what else you want.

Sorry for my exact request; I want get final result which looks like below:

[[[1, 2],
  [5, 6],
  [9, 10]],

 [[3, 4],
  [7, 8],
  [11, 12]]]

That's already what y is in my example. Do you want a Vec<Vec<Vec<_>>>, and if so, why?

yes, I want to Vec<Vec<Vec<_>>> for later more computation which is done once on one group, such as [[1, 2], [5, 6], [9, 10]]

You should probably not do that. The whole point of ndarray is that it can manage and process multi-dimensional arrays more efficiently, i.e., with a smaller number of allocations and fewer indirections. If you want to continue performing mathematical operations on the array, then leave it as the Array3 result that y is.

If you really, actually, positively need a nested Vec, then you can do this. It's not pretty, and it allocates a lot.

Thank you H2CO3;
I learn much from your reply.

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.