4

I can't quite figure out the syntax for this when using Eigen's rowwise operations...

I have an Eigen matrix, and I want to divide each row by the last row. So if we started with a matrix

r = [ 0, 1
      2, 3 
      4, 5 ]

then after this transform, I want to have

r = [  0, .2
      .5, .6
       1,  1 ]

Preferably the operation would happen in place, overwriting r. Furthermore, I will not be using the values in the last row, so it doesn't matter if the last row is actually 1's after the transform.

Here are some syntaxes I have tried that do not compile:

r.rowwise() = (r.array().rowwise() / r.bottomRows(1).array()).eval();
r.rowwise() = (r.rowwise().array() / r.bottomRows(1).array()).eval();
r.rowwise() /= r.bottomRows(1).array();
r = r.rowwise().cwiseQuotient(rrr);

This plain old for-loop version works

int last_row = r.rows() - 1;
for (int row = 0; row < last_row; ++row) {
    r.row(row).array() /= r.row(last_row).array();
}

However, everywhere I turn, people are advocating using the rowwise or colwise operations. I can't get this to work with that syntax. Is there a nice concise form of what I want to do using the rowwise operator?

bremen_matt
  • 6,902
  • 7
  • 42
  • 90

2 Answers2

4

To complete the self-answer, in case you don't need the last row, you can use hnormalized:

result = r.colwise().hnormalized()

and with Eigen trunk you can also write:

using namespace Eigen::placeholders::last;
r.array().rowwise() /= r.row(last).array();
ggael
  • 28,425
  • 2
  • 65
  • 71
2

Of course, I finally find the correct syntax after posting...

int last_row = r.rows() - 1;
r.array().rowwise() /= r.row(last_row).array();

For some reason, using bottomRows here leads to a compilation error. That is, the following does not compile

r.array().rowwise() /= r.bottomRows(1).array();
bremen_matt
  • 6,902
  • 7
  • 42
  • 90