按第 1 列值的升序对特征矩阵列值进行排序

use*_*420 7 c++ sorting matrix

我在 Eigen 中有 anx 3 矩阵。我想通过按升序对第一列中的值进行排序来重新排列第二列和第三列的值。例如在排序之前:

  1  4  6
 -2  5  2
  3  1  0
Run Code Online (Sandbox Code Playgroud)

按照第 1 列值的升序排序后:

 -2 5 2
  1 4 6
  3 1 0
Run Code Online (Sandbox Code Playgroud)

我不知道如何解决这个问题。我可以将每一列读入一个向量,并使用 std::sort 对第 1 列向量进行排序,但我不知道如何为第 1 列中的排序值保留第 2 列和第 3 列中的相应值。n 的值是已知的并已修复(如果有任何帮助的话)。

Seb*_*icz 1

这不太漂亮,并且依赖于使用模板参数来分解矩阵 - 但它是有效的。

#include <Eigen/Core>
#include <algorithm>
#include <vector>

// Simple little templated comparison functor
template <typename MatrixT>
bool compareRows(MatrixT a, MatrixT b) {
    return a(0,0) < b(0,0);
}

// These are the 6 template arguments to every Eigen matrix
template <typename Scalar, int rows, int cols, int options, int maxRows, int maxCols> 
Eigen::Matrix<Scalar, rows, cols, options, maxRows, maxCols> sortMatrix(
    Eigen::Matrix<Scalar, rows, cols, options, maxRows, maxCols> target
) {
    // Manually construct a vector of correctly-typed matrix rows
    std::vector<Eigen::Matrix<Scalar, 1, cols>> matrixRows;
    for (unsigned int i = 0; i < target.rows(); i++) 
            matrixRows.push_back(target.row(i));
    std::sort(
            matrixRows.begin(),
            matrixRows.end(),
            compareRows<Eigen::Matrix<Scalar, 1, cols>>
    );

    Eigen::Matrix<Scalar, rows, cols, options, maxRows, maxCols> sorted;
    for (unsigned int i = 0; i < matrixRows.size(); i++)
            sorted.row(i) = matrixRows[i];
    return sorted;
}
Run Code Online (Sandbox Code Playgroud)

值得庆幸的是,由于模板参数推导,你可以简单地这样称呼这个混乱:

Eigen::Matrix3f myMatrix;
// Fill in contents here
Eigen::Matrix3f sorted = sortMatrix(myMatrix);
Run Code Online (Sandbox Code Playgroud)

我几乎肯定有一种更优雅的方法可以做到这一点,但我现在想不到。而且,因为它使用std::vector,所以您需要使用-std=c++11或更好的版本进行编译。