ndarray icon indicating copy to clipboard operation
ndarray copied to clipboard

Create 2d array from matrix product of 1d arrays

Open ModProg opened this issue 1 year ago • 1 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.

ModProg avatar Jun 25 '23 12:06 ModProg

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());

adamreichold avatar Jun 25 '23 13:06 adamreichold