首先要說這個工具包非常的方便,解壓出來就可以用了。在工程裡面加入這個文件夾的路徑就可以了。
下面是一些代碼的練習:
#include#include using namespace Eigen; using namespace std; int main() { MatrixXd m = MatrixXd::Random(3,3); MatrixXd n; n=MatrixXd::Constant(3,3,1.2); //這是一個3*3的矩陣,裡面的值全部是1。2 cout << "n =" << endl << n << endl; m = (m + MatrixXd::Constant(3,3,1.2)) * 50; cout << "m =" << endl << m << endl; VectorXd v(3); v << 1, 2, 3; // 以下的結果說明是列向量3*1的。 cout << "m * v =" << endl << m * v << endl; return 0; }
下面會用到轉置:
#include#include using namespace Eigen; int main() { Matrix2d mat; mat << 1, 2, 3, 4; Vector2d u(-1,1), v(2,0); std::cout << "Here is mat*mat:\n" << mat*mat << std::endl; std::cout << "Here is mat*u:\n" << mat*u << std::endl; std::cout << "Here is u^T*mat:\n" << u.transpose()*mat << std::endl; //可以看出來.transpose()用來求轉置 std::cout << "Here is u^T*v:\n" << u.transpose()*v << std::endl; std::cout << "Here is u*v^T:\n" << u*v.transpose() << std::endl; std::cout << "Let's multiply mat by itself" << std::endl; mat = mat*mat; std::cout << "Now mat is mat:\n" << mat << std::endl; }
#include#include using namespace std; int main() { Eigen::MatrixXf m(4,4); m << 1, 2, 3, 4, 5, 6, 7, 8, 9,10,11,12, 13,14,15,16; cout << "Block in the middle" << endl; // 兩種不同的方式 cout << m.block<2,3>(1,1) << endl << endl; cout << "other kind Block in the middle" << endl; cout << m.block(1,1,2,3) << endl << endl; for (int i = 1; i <= 3; ++i) { cout << "Block of size " << i << "x" << i << endl; cout << m.block(0,0,i,i) << endl << endl; } }
#include#include using namespace std; int main() { Eigen::ArrayXf v(6); v << 1, 2, 3, 4, 5, 6; cout << "v.head(3) =" << endl << v.head(3) << endl << endl; cout << "v.tail<3>() = " << endl << v.tail<3>() << endl << endl; v.segment(1,4) *= 2; cout << "after 'v.segment(1,4) *= 2', v =" << endl << v << endl; //這裡選出第2和第5個數來分別的*2 Eigen::VectorXf v1(6); //可以看出來是一樣的 v1 << 1 ,2 ,2 , 4, 5, 6; cout << "v1.head(3) =" << endl << v1.head(3) << endl << endl; cout << "v.tail<3>() = " << endl << v1.tail<3>() << endl << endl; v1.segment(1,4) *= 2; cout << "after 'v.segment(1,4) *= 2', v =" << endl << v1 << endl; }
下來看一下基本的賦值情況:
#include#include #define SIZE 2 using namespace std; using namespace Eigen; void main() { MatrixXi m(SIZE,SIZE+1); // a (size)x(size+1)-matrix of int's cout<
下面的這張賦值方式:注意之間用的是逗號“ ,”#include#include #define SIZE 2 using namespace std; using namespace Eigen; void main() { int rows=5, cols=5; MatrixXf m(rows,cols); m << (Matrix3f() << 1, 2, 3, 4, 5, 6, 7, 8, 9).finished(),//不一樣的賦值方式e .finished() is used to get the actual matrix object once the comma initialization of our temporary submatrix is done. MatrixXf::Zero(3,cols-3),//用0來填補 MatrixXf::Zero(rows-3,3), MatrixXf::Identity(rows-3,cols-3);//用單位矩陣來填補最下面的矩陣 cout << m<