Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ Sign function - From MatLab?

Tags:

c++

matlab

sign

I'm trying to re-write some MatLab code in C++ and I've come across this:

currentsign = sign(vector(i));

I have looked on the internet and found this link: http://www.mathworks.co.uk/help/techdoc/ref/sign.html

I'm just wondering if there's a sign function in C++? If not, can anyone suggest any tutorials on creating it.

Thank you :)

like image 641
Phorce Avatar asked Dec 19 '25 18:12

Phorce


1 Answers

template <typename T>
int sign (const T &val) { return (val > 0) - (val < 0); }

Credit due to Ambroz Bizjak.

template <typename T>
std::vector<int> sign (const std::vector<T> &v) {
    std::vector<int> r(v.size());
    std::transform(v.begin(), v.end(), r.begin(), (int(*)(const T&))sign);
    return r;
}

Full example on ideone.

like image 82
jxh Avatar answered Dec 21 '25 09:12

jxh



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!