I am trying to use Rust to perform sequential kronecker product to multiple matrices, i.e. I want to do
In python, I know I can do
import numpy as np
from functools import reduce
X = np.array([[0, 1], [1, 0])
matrices = [X for _ in range(8)]
product = reduce(np.kron, matrices)
and get the desired result. How to do the same in Rust?
My Rust code look like the following for now:
use ndarray::{array, ArrayBase, OwnedRepr, Dim};
use ndarray::linalg::kron;
use num::complex::Complex64 as Complex;
fn X() -> ArrayBase<OwnedRepr<Complex>, Dim<[usize; 2]>> {
array![
[Complex::new(0.0, 0.0), Complex::new(1.0, 0.0)],
[Complex::new(1.0, 0.0), Complex::new(0.0, 0.0)]
]
}
fn main() {
let mut matrices = Vec::new();
for _ in 0..8 {
matrices.push(X());
}
let product = matrices
.iter()
.reduce(|g1, g2| kron(g1, g2));
}
Here's the error matrix I got:
Here's the things I don't understand:
OwnedRepr: I'm not sure what this is for exactly, but this is what the rust-analyzer suggested me to do- I tried to modify my code according to the error message's suggestion, but I got
with no further suggestions on how to process.
How can I achieve this?


Unlike Python, in Rust you are required to think about ownership.
ndarrayincludes multiple version of arrays:Array,ArrayView,ArrayViewMut,ArcArrayandCowArray. They are analogous to the many ways one can view a data in Rust: owned (TorBox<T>) - this isArraywhich is an alias ofArrayBase<OwnedRepr>, shared reference (&T) -ArrayView, mutable reference (&mut T) -ArrayViewMut, shared ownership (Rc<T>andArc<T>) -ArcArray, and copy-on-write (Cow<T>) -CowArray.iter()gives you an iterator over references to the elements, that is,&Array, whilekron()returns owned arrays -Array. Butreduce()requires both the inputs and the output to be of the same type, because the output becomes the input of the next item. So you need to unify them.There are multiple ways you can do that. For example, by using
into_iter()instead ofiter():Or by cloning the first matrix and using
fold():Or without cloning, by using
CowArrayto represent a maybe-owned array: