intmain() { Eigen::MatrixXd m(3, 3); m << 1, 2, 3, 4, 5, 6, 7, 8, 9; cout << "The matrix m is of size " << m.rows() << "x" << m.cols() << ", with " << m.size() << " cofficients." << endl; cout << "m:\n" << m << endl;
m.resize(4, 4); cout << "After resize(4,4), the matrix m is of size " << m.rows() << "x" << m.cols() << ", with " << m.size() << " cofficients." << endl; cout << "m:\n" << m << endl;
return0; }
输出:
1 2 3 4 5 6 7 8 9 10 11
The matrix m is of size 3x3, with 9 cofficients. m: 1 2 3 4 5 6 7 8 9 After resize(4,4), the matrix m is of size 4x4, with 16 cofficients. m: 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
intmain() { Eigen::MatrixXd m(3, 3); m << 1, 2, 3, 4, 5, 6, 7, 8, 9; cout << "The matrix m is of size " << m.rows() << "x" << m.cols() << ", with " << m.size() << " cofficients." << endl; cout << "m:\n" << m << endl;
m.conservativeResize(4, 4); cout << "After conservativeResize(4,4), the matrix m is of size " << m.rows() << "x" << m.cols() << ", with " << m.size() << " cofficients." << endl; cout << "m:\n" << m << endl;
m.conservativeResize(2, 2); cout << "After conservativeResize(2,2), the matrix m is of size " << m.rows() << "x" << m.cols() << ", with " << m.size() << " cofficients." << endl; cout << "m:\n" << m << endl;
return0; }
输出:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
The matrix m is of size 3x3, with 9 cofficients. m: 1 2 3 4 5 6 7 8 9 After conservativeResize(4,4), the matrix m is of size 4x4, with 16 cofficients. m: 1 2 3 0 4 5 6 0 7 8 9 0 0 0 0 0 After conservativeResize(2,2), the matrix m is of size 2x2, with 4 cofficients. m: 1 2 4 5
intmain() { Eigen::MatrixXd m(3, 3); m << 1, 2, 3, 4, 5, 6, 7, 8, 9; cout << "The matrix m is of size " << m.rows() << "x" << m.cols() << ", with " << m.size() << " cofficients." << endl; cout << "m:\n" << m << endl;
Eigen::MatrixXd n(2, 2); cout << "The matrix n is of size " << n.rows() << "x" << n.cols() << ", with " << n.size() << " cofficients." << endl; cout << "n:\n" << n << endl;
n = m; cout << "After assignment, the matrix n is of size " << n.rows() << "x" << n.cols() << ", with " << n.size() << " cofficients." << endl; cout << "n:\n" << n << endl;
return0; }
输出:
1 2 3 4 5 6 7 8 9 10 11 12 13 14
The matrix m is of size 3x3, with 9 cofficients. m: 1 2 3 4 5 6 7 8 9 The matrix n is of size 2x2, with 4 cofficients. n: 0 0 0 0 After assignment, the matrix n is of size 3x3, with 9 cofficients. n: 1 2 3 4 5 6 7 8 9
如果左侧为固定大小矩阵,编译不会报错。但如果大小与右侧不同,执行时会报错;相同则不会。
固定大小 vs. 动态大小
固定大小:适用于小矩阵(尤其是个数≤16的矩阵)。固定大小避免了动态内存分配并展开循环,有利于提高性能。实际上一个固定大小的Eigen矩阵只是一个简单的数组,即:执行 Matrix4f m 实际上就是在做 float m[16] 这件事,所以几乎不花时间。但需要注意的是,Eigen默认将数组自动分配为局部变量,这个操作在堆栈(stack)上完成,因此矩阵太大可能会导致堆栈溢出,并且矩阵太大(≥32)时,使用固定大小的性能优势就变得可以忽略不计了。
Matrix<typename Scalar, int RowsAtCompileTime, int ColsAtCompileTime, int Options = 0, int MaxRowsAtCompileTime = RowsAtCompilTime, int MaxColsAtCompileTime = ColsAtCompilTime>