Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Support things like matrix > scalar? Or matrix.greater_than(scalar)? #1087

Open
fzyzcjy opened this issue Oct 23, 2021 · 4 comments
Open

Support things like matrix > scalar? Or matrix.greater_than(scalar)? #1087

fzyzcjy opened this issue Oct 23, 2021 · 4 comments

Comments

@fzyzcjy
Copy link

fzyzcjy commented Oct 23, 2021

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?

@jturner314
Copy link
Member

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.

@fzyzcjy
Copy link
Author

fzyzcjy commented Oct 24, 2021

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.

@jturner314
Copy link
Member

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.

@fzyzcjy
Copy link
Author

fzyzcjy commented Oct 24, 2021

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants