Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

find rowwise maxCoeff and Index of maxCoeff in Eigen

Tags:

eigen

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.)

like image 810
Florian Oswald Avatar asked Jul 11 '12 10:07

Florian Oswald


2 Answers

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] );
like image 188
Jakob Avatar answered Nov 13 '22 11:11

Jakob


Besides the "for loop" solution by Jakob, you could also use libigl's igl::mat_max which functions like MATLAB's row-/column-wise max

Eigen::MatrixXf mat(2,4);
mat << 1, 2, 6, 9,
       3, 1, 7, 2;
Eigen::VectorXi maxIndices;
Eigen::VectorXf maxVals;
igl::mat_max(mat,2,maxVals,maxIndices);

Then maxVals would contain [9;7] and maxIndices would contain [3;2].

like image 2
Alec Jacobson Avatar answered Nov 13 '22 10:11

Alec Jacobson