rust-ndarray / ndarray

ndarray: an N-dimensional array with array views, multidimensional slicing, and efficient operations
https://docs.rs/ndarray/
Apache License 2.0
3.61k stars 306 forks source link

Complexification of a vector #1259

Closed SimonG85 closed 1 year ago

SimonG85 commented 1 year ago

Hi all,

I'm implementing a function to complexify a vector, namely if x is a vector its complexification is equal to x + i*x. I wrote the following function:

pub fn complexification<A, D>(arr: ArrayView<A, D>) -> Array<Complex, Ix1> where A: std::clone::Clone, D: Dimension, { arr.view() .iter() .zip(arr.view().iter()) .map(|(r, i)| Complex::new(r.clone(), i.clone())) .collect::<Array<Complex, _>>() }

Is it possibile to optimize/parallelize this function (maybe with rayon)? I'm at the beginning of rust and ndarray.

Thanks

jturner314 commented 1 year ago

This is the simplest way, and I suspect the compiler would do a good job making it fast:

use ndarray::prelude::*;
use num::Complex;

pub fn complexification<A, D>(arr: ArrayView<A, D>) -> Array<Complex<A>, D>
where
    A: Clone,
    D: Dimension,
{
    arr.map(|x| Complex::new(x.clone(), x.clone()))
}

fn main() {
    assert_eq!(
        complexification(aview1(&[1, 2])),
        array![Complex::new(1, 1), Complex::new(2, 2)],
    );
}

I doubt that it would make sense to parallelize this, since it's just copying data around, but if you want to read more about ndarray's parallelization functionality, see here: https://docs.rs/ndarray/0.15.6/ndarray/parallel/index.html

SimonG85 commented 1 year ago

Great advice. As usual, keep it simple!