Armadillo, finding the maximum index in each column

I am looking for a way to find the index corresponding to the maximum of each column. My goal is to avoid loops and find a Matlabic solution using the vectorized armadillo functions.

This is easy to do in Matlab with the following command: [~, maxIndices] = max (A);

In armadillo, you have a member function: A.max (row_of_max_val, col_of_max_val); which give the location of the maximum in the entire matrix.

And autonomous function vec M = max (A); which displays the maximum values โ€‹โ€‹of each column, but not their indices.

But none of them does the trick.

With columns, maximum indices can be used to write numerous algorithms in a more vectorial way. For example, it can be used in Viterbi decoding or in k-type clustering.

Obviously, this question can be generalized with minima instead of maxima and rows instead of columns.

Does anyone think of an alternative solution?

Best.

+6
source share
3 answers

Usually I use submatrix views. Something like that:

using idx_type = arma::uword; using namespace std; using namespace arma; template<typename T> vector<idx_type> colwise_max_idx(const Mat<T>& A) { vector<idx_type> res; for (idx_type i = 0; i != A.n_cols; ++i) { idx_type row_idx; A.col(i).max(row_idx); res.push_back(row_idx); } return res; } 
+6
source

The wrong answer would be something like this:

 uvec indices = find((A.each_row()-max(A)) == 0); 

Problems:

  • Multiple indexes can be returned for a unique column if the max element is present more than once.
  • Indexes are given relative to the first element of the matrix, not the first element of each column.
+1
source

Armadillo now has .index_max() and .index_min() methods for finding these indexes, starting with version 7.2.

0
source

All Articles