首页 > 解决方案 > Eigen 如何在容器循环中干净地附加矩阵?

问题描述

我有这个使用特征的代码:

struct Boundary
{
    Eigen::VectorXi VL;
    Eigen::MatrixXi EL;
    double length;
    bool isHole;
    bool isBoundary;
    bool isMainBoundary;
};

    int boundaryLoops = {};
    int boundariesNo = {};
    int holes = {};
    std::vector<Boundary> boundaries = {};

    MatrixXi SEUV;

    // ***** get all those boundaries here ****
    if (!CheckBoundaries(boundaryLoops, boundariesNo, holes, 
    boundaries))return false;

    // resize all loops container
    long size = {};
    for (auto &&boundary : boundaries){
        size += boundary.EL.rows();
    }
    SEUV.resize(size, 2);

    for (auto &&boundary : boundaries)
    {

        SEUV << boundary.EL; // Too few coefficients passed to comma initializer (operator<<)
        SEUV << SEUV, boundary.EL; // Too many rows passed to comma initializer (operator<<)
    }

除了通常的列数和行数之外,有没有一种快速的方法来做到这一点?这种情况经常发生,所以我正在寻找最干净的解决方案

谢谢

标签: c++matrixeigen

解决方案


如果要按行附加矩阵,则必须确保列数相等。

在调整矩阵大小之前,您还必须考虑先前的行数并存储矩阵。

SEUV << boundary.EL

失败,因为矩阵SEUV已经调整大小并且行数超过boundary.EL

SEUV << SEUV, boundary.EL

失败是因为SEUV占用了自身的所有空间,没有空间留给boundary.EL

这是一个示例,您如何附加 2 个具有 3 列和不同行的矩阵:

MatrixXi A(3,3);
A << 1, 1, 1, 1, 1, 1, 1, 1, 1;
cout << A << "\n\n";

MatrixXi B(2,3) ;
B << 2, 2, 2, 2, 2, 2;
cout << B << "\n\n";

MatrixXi tmp = A;
A.resize(A.rows() + B.rows(), NoChange);
A << tmp, B;
cout << A << "\n";

推荐阅读