This forum has been archived. All content is frozen. Please use KDE Discuss instead.

Extending cwise() with user-defined functions.

Tags: None
(comma "," separated)
djp
Registered Member
Posts
7
Karma
0
Hello,

quite regularly I need to apply a function, say myfunc(), coefficientwise to a matrix. Of course,
Code: Select all
MatrixXd A, B;
B = A.cwise().myfunc();

does not work, since Cwise only provides some standard functions.

If it is technically possible (I must admit that I don't understand the template magic behind Eigen well enough) I propose a templated version of MatrixBase::cwise()
Code: Select all
template cwise(F f);

where f is a function or functor that is to be applied coefficientwise, such that this code becomes possible
Code: Select all
B = A.cwise(myfunc);


Similar functions could be introduced for rowwise(F f) and colwise(F f), where f maps a vector to a scalar.

Best regards,
Martin
User avatar
bjacob
Registered Member
Posts
658
Karma
3
What you ask for is already available in Eigen, in two different forms.

First, see unaryExpr():
http://eigen.tuxfamily.org/dox/classEig ... 045c8a2e9e

there is an analogous static NullaryExpr(), by the way, and also binaryExpr().

The other approach is to write a plugin for the Cwise class. See this:
http://eigen.tuxfamily.org/api/Customiz ... MatrixBase
and just know that just like EIGEN_MATRIXBASE_PLUGIN, you can define EIGEN_CWISE_PLUGIN.


Join us on Eigen's IRC channel: #eigen on irc.freenode.net
Have a serious interest in Eigen? Then join the mailing list!
djp
Registered Member
Posts
7
Karma
0
Thanks a lot for your quick answer! I was indeed not aware of this function.

I do have a second, related question: Is it possible to specify the distribution of the random numbers generated by MatrixBase::Random()? In the documentation I could not find anything about this. I'm coming up with this question because my suggestion here would also be a template version of Random() which takes a RNG function of function object as parameter.
For example, using C++1x stuff:
Code: Select all
// Copied from Wikipedia
std::uniform_int_distribution distribution(0, 99);
std::mt19937 engine;
auto generator = std::bind(distribution, engine);

VectorXi v(42);
v.setRandom(generator);


Best regards,
Martin

Edit: Well, probably this is exactly what can be done with the NullaryExpr() that you mentioned.

Last edited by djp on Sat Apr 25, 2009 11:24 pm, edited 1 time in total.


Bookmarks



Who is online

Registered users: Bing [Bot], Evergrowing, Google [Bot], rblackwell