I want to find the maximum values and indices by row of a matrix. I based this on an example on the eigen website (example 7).
#include <iostream>
#include <Eigen/Dense>
using namespace std;
using namespace Eigen;
int main()
{
MatrixXf mat(2,4);
mat << 1, 2, 6, 9,
3, 1, 7, 2;
MatrixXf::Index maxIndex;
VectorXf maxVal = mat.rowwise().maxCoeff(&maxIndex);
std::cout << "Maxima at positions " << endl;
std::cout << maxIndex << std::endl;
std::cout << "maxVal " << maxVal << endl;
}
Problem here is that my line
VectorXf maxVal = mat.rowwise().maxCoeff(&maxIndex);
is wrong. The original example has
float maxNorm = mat.rowwise().sum().maxCoeff(&maxIndex);
i.e. there is an additional reduction .sum() involved. any suggestions? I guess I just want the eigen equivalent to what in matlab I would write as
[maxval maxind] = max(mymatrix,[],2)
i.e. find maximum value and it's index over the second dimension of mymatrix and return in a (nrow(mymatrix),2) matrix. thanks!
(sent to the eigen list as well, sorry for cross-posting.)
My guess is that this is not possible without using a for loop using the current api. As you said yourself, you can get the vector of maximum row values using
VectorXf maxVal = mat.rowwise().maxCoeff();
As far as I can tell from the API Documentation for maxCoeff() it will only write back a single index value. Following code (untested) should give you what you want:
MatrixXf::Index maxIndex[2];
VectorXf maxVal(2);
for(int i=0;i<2;++i)
maxVal(i) = mat.row(i).maxCoeff( &maxIndex[i] );