2

I'm trying to find the rust equivalent of this python numpy code doing elementwise comparison of an array.

import numpy as np
np.arange(3) > 1

Here's my rust code:

use ndarray::Array1;
fn main() {
    let arr = Array1::<f64>::range(0.0, 3.0, 1.0);
    arr > 1.0 // doesn't work.
}

I could do this with a for loop, but I'm looking for the most idiomatic way of doing it.

Chad
  • 1,434
  • 1
  • 15
  • 30

2 Answers2

2

Use .map for element-wise operations:

fn main() {
    let v: Vec<_> = (0..3).map(|x| x > 1).collect();
    println!("{v:?}")
}

Output:

[false, false, true]

Playground

aedm
  • 5,596
  • 2
  • 32
  • 36
1

The answer comes straight out of documentation for the map method:
arr.map(|x| *x > 1.0)

playground

Chad
  • 1,434
  • 1
  • 15
  • 30