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

Efficient element-wise operations

Tags: None
(comma "," separated)
alex.flint
Registered Member
Posts
1
Karma
0
OS

Efficient element-wise operations

Mon Mar 21, 2011 4:13 pm
Hi,

I'm thinking of porting some of my research code to Eigen. There are several parts of my program that need to perform element-by-element operations over matrices, but I'm anxious about using myMatrix(rowIndex,colIndex) because that's presumably recomputing positions on each invocation. I was thinking of defining EIGEN_DEFAULT_TO_ROW_MAJOR and then just getting pointers to the beginning of each row, but it seems that row() returns a copy rather than a reference. Can I do something like:

Code: Select all
MatrixXf mat(m, n);
for (int i = 0; i < m; i++) {
  RowReference theRow = mat.row(i);
  for (int j = 0; j < n; j++) {
    // do some processing on theRow
  }
}


What type should "RowReference" be? I want the changes to mirror back into "mat".

Cheers,
Alex
jitseniesen
Registered Member
Posts
204
Karma
2

Re: Efficient element-wise operations

Mon Mar 21, 2011 10:05 pm
You can find this sort of information in the API documentation if you know where to look. The row() function is documented at http://eigen.tuxfamily.org/dox/classEig ... 8665c28813 . You'll see that it returns something of type RowXpr. This is a type member of MatrixXf, so in your code you would write the third line as "MatrixXf::RowXpr theRow = mat.row(i);" A RowXpr is basically a reference to the row, but once you assign it to a vector or a matrix it makes a copy.

However, depending on what you want to do, other solutions may be better. It sounds like the unaryExpr() function would be useful for you. Have a look at the example at http://eigen.tuxfamily.org/dox/classEig ... b0525ddd65 .
User avatar
ggael
Moderator
Posts
3447
Karma
19
OS

Re: Efficient element-wise operations

Mon Mar 21, 2011 11:28 pm
I'd go even farther by saying that in general you even do not need custom functors (unaryExpr/binaryExpr), but instead use Eigen's API to build complex and optimized expressions, e.g.:

(std::sin(m.row(i).array() + M_PI)).maxCoeff()

compiles to something like:

double* base = &m(i,0);
double res = sin(base[0] + M_PI);
for(int j=1; j<m.row(i).size();++j)
res = std::max(res, sin(base[j] + M_PI));

and in some cases this expression can even be unrolled and/or vectorized by Eigen for you!


Bookmarks



Who is online

Registered users: bartoloni, Bing [Bot], Evergrowing, Google [Bot], q.ignora