如何在Eigen中得到系数矩阵?

时间:2015-09-13 01:00:05

标签: c++ matrix eigen

好的,我想在Eigen做这个操作:

float StartMatrix[7][7] = { { 1, 4, 6, 9, 3, 5, 8 }, { 2, 5, 3, 7, 4, 8, 2 }, { 3, 6, 6, 7, 0, 2, 4 }, 
                            { 2, 4, 3, 7, 4, 8, 2 }, { 2, 3, 3, 11, 4, 8, 1 }, { 2, 12, 3, 7, 0, 8, 2 },
                            { 2, 2, 3, 4, 4, 11, 2 } };

float TotalMatrix[7] = { 22, 15, 13, 26, 27, 33, 19 };

float CoMatrix[7][7] = { { 0, 0, 0, 0, 0, 0, 0 }, { 0, 0, 0, 0, 0, 0, 0 }, { 0, 0, 0, 0, 0, 0, 0 },
                        { 0, 0, 0, 0, 0, 0, 0 }, { 0, 0, 0, 0, 0, 0, 0 }, { 0, 0, 0, 0, 0, 0, 0 }, 
                        { 0, 0, 0, 0, 0, 0, 0 } };

for (int row = 0; row < 7; row++) {
    for (int col = 0; col < 7; col++) {
        CoMatrix[row][col] = StartMatrix[row][col] / TotalMatrix[col];
    }

}

将每一行除以TotalMatrix中的列。然后我想从Eigen中的CoMatrix中减去Identity矩阵并得到相反的结果(只是想知道我为什么要这样做)。

问题是,如何使用Eigen执行此操作,或者以某种方式将CoMatrix数组放入Eigen中的矩阵中,这样我就能用它来做任务(比如反转等)。

谢谢!

1 个答案:

答案 0 :(得分:3)

你在Eigen中的代码看起来像这样(在导入Eigen命名空间后,using namespace Eigen;):

MatrixXd StartMatrix(7, 7);
StartMatrix << 
    1, 4, 6, 9, 3, 5, 8, 2, 5, 3, 7, 4, 8, 2, 3, 6, 6, 7, 0, 2, 4,
    2, 4, 3, 7, 4, 8, 2, 2, 3, 3, 11, 4, 8, 1, 2, 12, 3, 7, 0, 8, 2,
    2, 2, 3, 4, 4, 11, 2;

VectorXd TotalMatrix(7);
TotalMatrix << 22, 15, 13, 26, 27, 33, 19;

MatrixXd CoMatrix = MatrixXd::Zero(StartMatrix.rows(), StartMatrix.cols());

CoMatrix = StartMatrix.array() / (TotalMatrix.replicate(1,StartMatrix.cols())).array();

您可以继续使用

减去单位矩阵
CoMatrix -= MatrixXd::Identity(CoMatrix.rows(), CoMatrix.cols());

或将其与前一个表达式合并为:

CoMatrix = (StartMatrix.array() / (TotalMatrix.replicate(1, StartMatrix.cols())).array()).matrix()
    - MatrixXd::Identity(CoMatrix.rows(), CoMatrix.cols());