Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Foreach loops over Eigen matrices?

Is it possible to use the foreach syntax of C++11 with Eigen matrices? For instance, if I wanted to compute the sum of a matrix (I know there's a builtin function for this, I just wanted a simple example) I'd like to do something like

Matrix2d a;
a << 1, 2,
     3, 4;
double sum = 0.0;
for(double d : a) {
  sum += d;
}

However Eigen doesn't seem to allow it. Is there a more natural way to do a foreach loop over elements of an Eigen matrix?

like image 333
David Pfau Avatar asked Nov 20 '14 02:11

David Pfau


2 Answers

For your particular case, it's more useful to obtain start and end iterators yourself, and pass both iterators to a standard algorithm:

auto const sum = std::accumulate(a.data(), a.data()+a.size(), 0.0);

If you have another function that really needs range-based for, you need to provide implementations of begin() and end() in the same namespace as the type (for argument-dependent lookup). I'll use C++14 here, to save typing:

namespace Eigen
{
    auto begin(Matrix2d& m) { return m.data(); }
    auto end(Matrix2d& m) { return m.data()+m.size(); }
    auto begin(Matrix2d const& m) { return m.data(); }
    auto end(Matrix2d const& m) { return m.data()+m.size(); }
}
like image 188
Toby Speight Avatar answered Oct 17 '22 15:10

Toby Speight


Range-based for loops need the methods .begin() and .end() to be implemented on that type, which they are not for Eigen matrices. However, as a pointer is also a valid random access iterator in C++, the methods .data() and .data() + .size() can be used for the begin and end functions for any of the STL algorithms.

like image 26
Simmovation Avatar answered Oct 17 '22 16:10

Simmovation