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

How to get the rowwise sum of a binary matrix?

Tags: None
(comma "," separated)
davidknowles
Registered Member
Posts
1
Karma
0
The following code doesn't compile, saying YOU_MIXED_DIFFERENT_NUMERIC_TYPES__YOU_NEED_TO_USE_THE_CAST_METHOD_OF_MATRIXBASE_TO_CAST_NUMERIC_TYPES_EXPLICITLY
Code: Select all
 
  Matrix<bool,Dynamic,Dynamic> r(2,2);
  r << true,false,
    false,false;
  VectorXi a = r.rowwise().count();

However, I can cout the result:
Code: Select all
 
  Matrix<bool,Dynamic,Dynamic> r(2,2);
  r << true,false,
    false,false;
  cout << r.rowwise().count() << endl;

What type do I need to give a? And perhaps more importantly, how should I have found this out?
Thanks,
David
jitseniesen
Registered Member
Posts
204
Karma
2
This took me a couple of minutes to find out ... a should be of type Matrix<std::ptrdiff_t, Dynamic, 1> . One hint is that the error message includes member_count<long int>, and indeed on my 64-bits system, ptrdiff_t is long int. The second hint is that MatrixBase::count() returns an Index (see http://eigen.tuxfamily.org/dox-devel/cl ... fa6577ee00 ) and for dense matrices, Index is EIGEN_DEFAULT_DENSE_INDEX_TYPE (see http://eigen.tuxfamily.org/dox-devel/cl ... fa97fd5c40 ) is ptrdiff_t (see http://eigen.tuxfamily.org/dox-devel/To ... tives.html )

I'll try and clarify the documentation.
cherishing
Registered Member
Posts
2
Karma
0
Think that auto is a good way to do so and using cast is another way:
Code: Select all
   auto tmp=r.rowwise().count();
   Eigen::Matrix<int,Eigen::Dynamic,Eigen::Dynamic> rInt=r.rowwise().count().cast<int>();
jitseniesen
Registered Member
Posts
204
Karma
2
cast() is another good solution. auto may not do what you expect. After "auto tmp=r.rowwise().count();" the variable tmp contains an expression object which computes the rowwise sum of r whenever you read from it. So it's recomputed every time, and the value changes if r changes. I expect that in most applications you want to evaluate the expression object; that is, write (not tested)
Code: Select all
auto tmp = r.rowwise().count().eval();


Bookmarks



Who is online

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