Succinctly multiplying arrays/vectors by floats and trigonometric functions

Say I have an equation


Where a, b, c are f64 floats, and t is an array of some floats from 0 to 2pi. I've been trying to wrap my head around how I would succinctly apply an equation like this in Rust to calculate some array x. Obviously, steps like c * t won't work in Rust, so we can apply for_each commands like,

t.iter_mut().for_each(|val| *val *= c);

but then applying this kind of logic to all the operations of a, b, c and trigonometric functions, I think would trap me into writing some ugly spaghetti code. What's the correct way of going about this?

How about Mul in std::ops - Rust?

It will not be quite as convenient as in MATLAB or Python+NumPy, but you probably are looking for something like ndarray.

fn find_x(a: f64, b: f64, c: f64, t: ArrayView1<f64>) -> Array1<f64> {
    (a + b * (c*&t).mapv(f64::sin)) * t.mapv(f64::cos)

Playground with conversions from slice / to vec.

if t is really an array, you can use array::map, to apply the equation to each item, or if it's a vec you can use a regular iterator map+collect.

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.