Index of max coefficient (column wise) in Eigen
Asked Answered
D

1

6

In Eigen, I can do a row-wise or column-wise "partial reduction" to get the maximum coefficients.

For example, this program:

#include <iostream>
#include <Eigen/Dense>

int main()
{
  Eigen::MatrixXf mat(2,4);
  mat << 1, 2, 6, 9,
         3, 1, 7, 2;

  std::cout << "Column's maximum: " << std::endl
   << mat.colwise().maxCoeff() << std::endl;
}

Outputs:

Column's maximum:
3 2 7 9

Instead of creating a row vector with the maximum coefficient in each column, I would like to construct a row vector with the index of the maximum coefficient of each column.

In other words, I would like to modify the program so that the output becomes:

Column's maximum:
1, 0, 1, 0

I know I can get the index one column at a time doing something like this:

Eigen::MatrixXf::Index max_index;
mat.col(i).maxCoeff(&max_index);

but I was hoping there was a better way that could do this all in one step instead of manually looping through each column. Is this possible? (I'm using Eigen v3.2.7)

Detection answered 31/12, 2015 at 20:13 Comment(0)
D
2

I found a post on Eigen's user forums from 2012 that suggests this is not possible, and that looping over the rows/columns is indeed the best way.

There is no shorter way yet. Regarding vectorization, vec.maxCoeff() is vectorized (standard reduction), but not the version returning the index: vec.maxCoeff(int&). It's not impossible but I'd not expect significant gain if any.

I briefly grepped through some of the 3.2.7 code base, and it doesn't appear that anything has changed since the post.

Detection answered 4/1, 2016 at 14:19 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.