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

Printing a matrix with a user-defined scalar type

Tags: None
(comma "," separated)
koooooong
Registered Member
Posts
5
Karma
0
Hello,

I'm trying to get Eigen to work with a custom scalar type. In general, this has been quite easy, just following the instructions on the site. I can easily cast from doubles to my type, manipulate, etc. Almost everything is gravy. However, I am at a loss for how to get

cout << M << endl;

to work when M is a matrix with my custom scalar type. I have defined operator<< for my type. I get error messages like so:

eigen/Eigen/src/Core/IO.h:138: error: no match for 'operator<<' in 'sstr << (+ m)->Eigen::Matrix<_Scalar, _Rows, _Cols, _Options, _MaxRows, _MaxCols>::coeff [with _Scalar = etree, int _Rows = 10000, int _Cols = 1, int _Options = 2, int _MaxRows = 10000, int _MaxCols = 1](i, j)'

Any idea what I need to do to get this to work? Thanks in advance! (BTW, if any Eigen developers read this, the library is fantastic.)
koooooong
Registered Member
Posts
5
Karma
0
If this helps, I find I can print my matrix by doing

cout << M.cast<double>() << endl;

which is pretty tolerable, but I guess less than ideal.
User avatar
ggael
Moderator
Posts
3447
Karma
19
OS
Hi,

you have to implement operator<< for your custom type, e.g.:

Code: Select all
std::ostream & operator<< (std::ostream & s, const CustomScalarType& x)
{
  s << double(x);
  return s;
}
koooooong
Registered Member
Posts
5
Karma
0
Thanks for the reply.

Yes, I have implemented operator<< for my type. (In fact, my implementation is almost identical to yours.) So, I can print a scalar by doing

cout << a << endl;

but this doesn't work with an Eigen matrix of my scalar.

My guess was that I would need to specialize Eigen::Matrix's templated operator<< for my type or something like that, but I haven't been able to figure this out.
User avatar
ggael
Moderator
Posts
3447
Karma
19
OS
ok, but the compiler cannot find it, so:

1 - check that cout << m(0,0); works fine where m is an Eigen matrix with your scalar type

2 - check it works for stringstream:
std::stringstream sstr;
sstr << m(0,0);

3 - check twice the prototype of your operator<< (ostream, const ref, etc.)

4 - check your operator is defined before including Eigen.

If you still have issue could you please paste all error messages.

good luck
koooooong
Registered Member
Posts
5
Karma
0
Thank you, thank you, thank you! Those were some great instructions.

I am embarased to say that the problem was that I forgot to declare my type const in operator<<. In any case, I think your help here will be useful to others in the future.


Bookmarks



Who is online

Registered users: Bing [Bot], Google [Bot], Sogou [Bot]