rust-ndarray / ndarray

ndarray: an N-dimensional array with array views, multidimensional slicing, and efficient operations

Home Page:https://docs.rs/ndarray/

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Create 2d array from matrix product of 1d arrays

ModProg opened this issue · comments

I have two vectors, and want to multiply them to a 2d matrix by transposing one of them.

Currently I am using nalgebra + ndarray for that:

let a = // the 1d ndarray
let a = Vector::from(a.to_vec()); // convert to nalgebra
let a_adjoint = a.adjoint(); // transpose
let b = a * a_adjoint;  // create matrix in nalgebra
let b = Array2::from_shape_fn((a_len, a_len), |i| b [i]);

Both better integration with nalgebra (adding some From implementations through a feature flag) or supporting this operation directly would help.

Maybe there is a better way to do this I'm not seeing.

How about doing this directly with from_shape_fn, e.g.

let b = Array::from_shape_fn((a_len, a_len), |(i, j)| a[i] * a[j]);

If you want a point-free version, then I think this requires broadcasting, e.g.

let aa = a.broadcast((a_len, a_len)).unwrap();
let b = &aa * &aa.t());