rustnalgebra

nalgebra apply function to every element of a vector


sorry if this is a noob question but is it posible to apply a function to every element in a nalgebra vector?

if I for example have a vector like this:

type Vector2x1 = SVector<f32, 2>;
let vector = Vector2x1::new(2.0, 2.0);

how can I apply a function which takes a f32 as an argument to every element in the vector?


Solution

  • Re-stating @AlphaModder's comment, you can use the function map to do this. Alternativaley you could iterate over the elements and map each one, but .map(x) conveniently handles the other steps for you without the overhead (if any) of an iterator (Ex: .into_iter().map(x).collect::<Self>()).

    // Create a new Vector2<f32> (Same thing as SVector<f32, 2>)
    let vector: Vector2<f32> = Vector2::new(1.0, 2.0);
    
    // Use .map to apply a closure to each element
    let result = vector.map(|x: f32| x * 2.0);
    
    // Do something with the result
    assert_eq!(result, Vector2::new(2.0, 4.0));
    

    If you did not already know, you can also use a function in place of the closure.

    fn foo(x: f32) -> f32 {
        x + 1.0
    }
    
    let result = vector.map(foo);
    

    This approach will work for any variant of Vector or Matrix (impl<T, R: Dim, C: Dim, S: RawStorage<T, R, C>> Matrix<T, R, C, S>).