ndarray
ndarray copied to clipboard
Support things like `matrix > scalar`? Or `matrix.greater_than(scalar)`?
Hi thanks for the lib! After looking at doc, it seems that we do not have the things mentioned in the title yet. Can we implement it?
I guess > must return bool in Rust so we cannot do that easily. But can we have a function like ge/gt/greater_than?
map and mapv can be used for this purpose. I'm not sure that it would be worthwhile to add a bunch of specific methods.
Thank you! The use case: I am porting python numpy code to rust (you know, from research experiment to industry product). So there are a lot of things like a > 50/a != 100 etc where a is np array.
I understand, although I'm still not sure these should be added to ndarray itself. Keep in mind that you can always create your own extension traits, e.g.:
use ndarray::prelude::*;
use ndarray::Data;
pub trait CompareScalarExt<Rhs> {
type Elem: PartialOrd<Rhs>;
type Dim;
fn lt(&self, scalar: &Rhs) -> Array<bool, Self::Dim>;
// ...
}
impl<A, S, D, Rhs> CompareScalarExt<Rhs> for ArrayBase<S, D>
where
A: PartialOrd<Rhs>,
S: Data<Elem = A>,
D: Dimension,
{
type Elem = A;
type Dim = D;
fn lt(&self, scalar: &Rhs) -> Array<bool, D> {
self.map(move |elem| elem < scalar)
}
// ...
}
fn main() {
let a = array![1, 2, 3];
assert_eq!(a.lt(&2), array![true, false, false]);
}
You may also be interested in PR #1042, which is similar in spirit to this issue, but for float math functions.
Thank you! After my reply, I have made a proc macro. Now I can use:ops!{ (matrix_one > 42) & (matrix_two != matrix_three) } etc, and the operators such as >, ==, ... will be translated correctly. If you are interested, I can open-source this.