Search code examples
c++eigen

Efficient way to find maximum value of Sparse matrix (Eigen)


I was wondering whether it is possible to find the max/min coefficients in a sparse matrix in an efficient way.

It seems that the minCoeff()/maxCoeff() functions are not implemented for sparse matrices, which is a bit weird.

I found this answer here, but I could not figure it out.

 using Tmp = typename remove_cv_ref<decltype(matrix)>::type;
 if constexpr(std::is_base_of<Eigen::SparseMatrixBase<Tmp>, Tmp>::value)
 max = Eigen::Map<const Vector>(matrix.valuePtr(), matrix.size()).maxCoeff();
 else
    max = matrix.maxCoeff();

Edit: This is my try, I am not sure about the efficiency.

typedef Eigen::SparseMatrix<int, Eigen::RowMajor> SRI;
int maxCoeff(const SparseMatrix<int, RowMajor> &A)
{
    size_t row = A.rows();
    size_t col = A.cols();
    int max_value = -10000000;
    for (size_t k = 0; k < row; k++)
    {
        for (SRI::InnerIterator it(A, k); it; ++it)
        {
            if (it.value() > max_value)
                max_value = it.value();
        }
    }
    return max_value;
}

Solution

  • Those functions are not readily available because it might be ambiguous whether the implicit zeros should be taken into account or not. For instance, if all non-zeros are negative, shall maxCoeff returns 0?

    If you want to consider explicitly stored elements only and that your sparse matrix in is compressed mode, then you can write:

    auto max = matrix.coeffs().maxCoeff();
    

    The coeff method is equivalent to RHertel's answer.