// a is a 3-by-3 matrix, with a plain float[9] array of
// uninitialized coefficients,
Matrix3fa;// b is a dynamic-size matrix whose size is currently 0-by-0,
// and whose array of coefficients hasn't yet been allocated at all.
MatrixXfb;MatrixXfa(10,15);VectorXfb(30);
#include<iostream>#include<Eigen/Dense>usingnamespaceEigen;intmain(){MatrixXdm(2,2);m(0,0)=3;m(1,0)=2.5;m(0,1)=-1;m(1,1)=m(1,0)+m(0,1);std::cout<<"Here is the matrix m:\n"<<m<<std::endl;VectorXdv(2);v(0)=4;v(1)=v(0)-1;std::cout<<"Here is the vector v:\n"<<v<<std::endl;}
#include<Eigen/Dense>#include<iostream>usingnamespacestd;intmain(){Eigen::MatrixXfm(3,3);m<<1,2,3,4,5,6,7,8,9;cout<<"Here is the matrix m:"<<endl<<m<<endl;cout<<"2nd Row: "<<m.row(1)<<endl;m.col(2)+=3*m.col(0);cout<<"After adding 3 times the first column into the third column, the matrix m is:\n";cout<<m<<endl;}
shape相关
rows() 获取行数
cols() 获取列数
size() 获取元素的个数
resize() 修改shape (元素的值可能会产生变化)
conservativeResize() 修改shape (元素的值可保留)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
#include<iostream>#include<Eigen/Dense>usingnamespaceEigen;intmain(){MatrixXdm(2,5);m.resize(4,3);std::cout<<"The matrix m is of size "<<m.rows()<<"x"<<m.cols()<<std::endl;std::cout<<"It has "<<m.size()<<" coefficients"<<std::endl;VectorXdv(2);v.resize(5);std::cout<<"The vector v is of size "<<v.size()<<std::endl;std::cout<<"As a matrix, v is of size "
赋值
setZero()
fill(val)
setOnes()
setRandom()
1
2
3
4
5
6
7
8
9
MatrixXfa(2,2);std::cout<<"a is of size "<<a.rows()<<"x"<<a.cols()<<std::endl;MatrixXfb(3,3);a=b;std::cout<<"a is now of size "<<a.rows()<<"x"<<a.cols()<<std::endl;m1.setZero();// 赋值全为0
m1.fill(2);// 赋值全为2
m1.setOnes();// 赋值全为1
m1.setRandom();// 赋值为随机数
// Eigen Matrix plus a scalar
template<classDerived,classType>voidPlusScalar(MatrixBase<Derived>&m1,Typenum){introws=m1.rows(),cols=m1.cols();m1=m1+num*MatrixBase<Derived>::Constant(rows,cols,num);}// Eigen Matrix minus a scalar
template<classDerived,classType>voidMinusScalar(MatrixBase<Derived>&m1,Typenum){introws=m1.rows(),cols=m1.cols();m1=m1-num*MatrixBase<Derived>::Constant(rows,cols,num);}
转置与共轭
transpose()
conjugate()
adjoint()
1
2
3
4
5
MatrixXcfa=MatrixXcf::Random(2,2);cout<<"Here is the matrix a\n"<<a<<endl;cout<<"Here is the matrix a^T\n"<<a.transpose()<<endl;cout<<"Here is the conjugate of a\n"<<a.conjugate()<<endl;cout<<"Here is the matrix a^*\n"<<a.adjoint()<<endl;
In place 的转置
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
Matrix2ia;a<<1,2,3,4;cout<<"Here is the matrix a:\n"<<a<<endl;a=a.transpose();// !!! do NOT do this !!!
cout<<"and the result of the aliasing effect:\n"<<a<<endl;=>Hereisthematrixa:1234andtheresultofthealiasingeffect:1224MatrixXfa(2,3);a<<1,2,3,4,5,6;cout<<"Here is the initial matrix a:\n"<<a<<endl;a.transposeInPlace();cout<<"and after being transposed:\n"<<a<<endl;
#include<iostream>#include<Eigen/Dense>usingnamespaceEigen;intmain(){Matrix2dmat;mat<<1,2,3,4;Vector2du(-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;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;}=>Hereismat*mat:7101522Hereismat*u:11Hereisu^T*mat:22Hereisu^T*v:-2Hereisu*v^T:-2-020Let'smultiplymatbyitselfNowmatismat:7101522
#include<iostream>#include<Eigen/Dense>usingnamespaceEigen;usingnamespacestd;intmain(){Vector3dv(1,2,3);Vector3dw(0,1,2);cout<<"Dot product: "<<v.dot(w)<<endl;doubledp=v.adjoint()*w;// automatic conversion of the inner product to a scalar
cout<<"Dot product via a matrix product: "<<dp<<endl;cout<<"Cross product:\n"<<v.cross(w)<<endl;}=>Dotproduct:8Dotproductviaamatrixproduct:8Crossproduct:1-21
#include<iostream>#include<Eigen/Dense>usingnamespacestd;intmain(){Eigen::Matrix2dmat;mat<<1,2,3,4;cout<<"Here is mat.sum(): "<<mat.sum()<<endl;cout<<"Here is mat.prod(): "<<mat.prod()<<endl;cout<<"Here is mat.mean(): "<<mat.mean()<<endl;cout<<"Here is mat.minCoeff(): "<<mat.minCoeff()<<endl;cout<<"Here is mat.maxCoeff(): "<<mat.maxCoeff()<<endl;cout<<"Here is mat.trace(): "<<mat.trace()<<endl;}=>Hereismat.sum():10Hereismat.prod():24Hereismat.mean():2.5Hereismat.minCoeff():1Hereismat.maxCoeff():4Hereismat.trace():5
#include<iostream>#include<Eigen/Dense>usingnamespacestd;usingnamespaceEigen;intmain(){Eigen::MatrixXfm(2,2);m<<1,2,3,4;//get location of maximum
MatrixXf::IndexmaxRow,maxCol;floatmax=m.maxCoeff(&maxRow,&maxCol);//get location of minimum
MatrixXf::IndexminRow,minCol;floatmin=m.minCoeff(&minRow,&minCol);cout<<"Max: "<<max<<", at: "<<maxRow<<","<<maxCol<<endl;cout<<"Min: "<<min<<", at: "<<minRow<<","<<minCol<<endl;}=>Max:4,at:1,1Min:1,at:0,0
Map<Matrix<typename Scalar, int RowsAtCompileTime, int ColsAtCompileTime> >
初始化
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
Map<MatrixXf>mf(pf,rows,columns);Map<constVector4i>mi(pi);// convert STL vector to Eigen Vector
vector<int>local_vec;for(inti=0;i<3;i++){local_vec.push_back(i);}Map<MatrixXi>local_v(local_vec.data(),1,local_vec.size());vector<double>mv;for(inti=0;i<5;i++){for(intj=0;j<3;j++){mv.push_back(i);}}Map<MatrixD>X(mv.data(),3,5);
typedefMatrix<float,1,Dynamic>MatrixType;typedefMap<MatrixType>MapType;typedefMap<constMatrixType>MapTypeConst;// a read-only map
constintn_dims=5;MatrixTypem1(n_dims),m2(n_dims);m1.setRandom();m2.setRandom();float*p=&m2(0);// get the address storing the data for m2
MapTypem2map(p,m2.size());// m2map shares data with m2
MapTypeConstm2mapconst(p,m2.size());// a read-only accessor for m2
cout<<"m1: "<<m1<<endl;cout<<"m2: "<<m2<<endl;cout<<"Squared euclidean distance: "<<(m1-m2).squaredNorm()<<endl;cout<<"Squared euclidean distance, using map: "<<(m1-m2map).squaredNorm()<<endl;m2map(3)=7;// this will change m2, since they share the same array
cout<<"Updated m2: "<<m2<<endl;cout<<"m2 coefficient 2, constant accessor: "<<m2mapconst(2)<<endl;/* m2mapconst(2) = 5; */// this yields a compile-time error
=>m1:0.68-0.2110.5660.5970.823m2:-0.605-0.330.536-0.4440.108Squaredeuclideandistance:3.26Squaredeuclideandistance,usingmap:3.26Updatedm2:-0.605-0.330.53670.108m2coefficient2,constantaccessor:0.536
改变Map的数组需要使用new:
1
2
3
4
5
6
7
8
intdata[]={1,2,3,4,5,6,7,8,9};Map<RowVectorXi>v(data,4);cout<<"The mapped vector v is: "<<v<<"\n";new(&v)Map<RowVectorXi>(data+4,5);cout<<"Now v is: "<<v<<"\n";=>Themappedvectorvis:1234Nowvis:56789
1
2
3
4
5
6
7
Map<Matrix3f>A(NULL);// don't try to use this matrix yet!
VectorXfb(n_matrices);for(inti=0;i<n_matrices;i++){new(&A)Map<Matrix3f>(get_matrix_pointer(i));b(i)=A.trace();}
MatrixXfM1=MatrixXf::Random(3,8);cout<<"Column major input:"<<endl<<M1<<"\n";Map<MatrixXf,0,OuterStride<>>M2(M1.data(),M1.rows(),(M1.cols()+2)/3,OuterStride<>(M1.outerStride()*3));cout<<"1 column over 3:"<<endl<<M2<<"\n";typedefMatrix<float,Dynamic,Dynamic,RowMajor>RowMajorMatrixXf;RowMajorMatrixXfM3(M1);cout<<"Row major input:"<<endl<<M3<<"\n";Map<RowMajorMatrixXf,0,Stride<Dynamic,3>>M4(M3.data(),M3.rows(),(M3.cols()+2)/3,Stride<Dynamic,3>(M3.outerStride(),3));cout<<"1 column over 3:"<<endl<<M4<<"\n";=>Columnmajorinput:0.680.597-0.330.108-0.270.832-0.717-0.514-0.2110.8230.536-0.04520.02680.2710.214-0.7260.566-0.605-0.4440.2580.9040.435-0.9670.6081columnover3:0.680.108-0.717-0.211-0.04520.2140.5660.258-0.967Rowmajorinput:0.680.597-0.330.108-0.270.832-0.717-0.514-0.2110.8230.536-0.04520.02680.2710.214-0.7260.566-0.605-0.4440.2580.9040.435-0.9670.6081columnover3:0.680.108-0.717-0.211-0.04520.2140.5660.258-0.967
MatrixXimat(3,3);mat<<1,2,3,4,5,6,7,8,9;cout<<"Here is the matrix mat:\n"<<mat<<endl;// The eval() solves the aliasing problem
mat.bottomRightCorner(2,2)=mat.topLeftCorner(2,2).eval();cout<<"After the assignment, mat = \n"<<mat<<endl;
typedefMatrix<double,5,3>Matrix5x3;typedefMatrix<double,5,5>Matrix5x5;Matrix5x3m=Matrix5x3::Random();cout<<"Here is the matrix m:"<<endl<<m<<endl;Eigen::FullPivLU<Matrix5x3>lu(m);cout<<"Here is, up to permutations, its LU decomposition matrix:"<<endl<<lu.matrixLU()<<endl;cout<<"Here is the L part:"<<endl;Matrix5x5l=Matrix5x5::Identity();l.block<5,3>(0,0).triangularView<StrictlyLower>()=lu.matrixLU();cout<<l<<endl;cout<<"Here is the U part:"<<endl;Matrix5x3u=lu.matrixLU().triangularView<Upper>();cout<<u<<endl;cout<<"Let us now reconstruct the original matrix m:"<<endl;cout<<lu.permutationP().inverse()*l*u*lu.permutationQ().inverse()<<endl;=>Hereisthematrixm:0.68-0.605-0.0452-0.211-0.330.2580.5660.536-0.270.597-0.4440.02680.8230.1080.904Hereis,uptopermutations,itsLUdecompositionmatrix:0.9040.8230.108-0.2990.8120.569-0.050.888-1.10.02960.7050.7680.285-0.5490.0436HereistheLpart:10000-0.2991000-0.050.8881000.02960.7050.768100.285-0.5490.043601HereistheUpart:0.9040.8230.10800.8120.56900-1.1000000Letusnowreconstructtheoriginalmatrixm:0.68-0.605-0.0452-0.211-0.330.2580.5660.536-0.270.597-0.4440.02680.8230.1080.904
#include<iostream>#include<Library/eigen/Eigen/Dense>usingnamespaceEigen;usingnamespacestd;intmain(){MatrixXdA(3,3);A<<4,-1,2,-1,6,0,2,0,5;cout<<"The matrix A is"<<endl<<A<<endl;LLT<MatrixXd>lltOfA(A);// compute the Cholesky decomposition of A
MatrixXdL=lltOfA.matrixL();// retrieve factor L in the decomposition
// The previous two lines can also be written as "L = A.llt().matrixL()"
cout<<"The Cholesky factor L is"<<endl<<L<<endl;cout<<"To check this, let us compute L * L.transpose()"<<endl;cout<<L*L.transpose()<<endl;cout<<"This should equal the matrix A"<<endl;}
利用Cholesky分解求解方程
求解方程$Ax=b$,使用该方法默认矩阵$A$可逆。
例子1:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
#include<iostream>#include<Library/eigen/Eigen/Dense>usingnamespaceEigen;typedefMatrix<float,Dynamic,2>DataMatrix;usingnamespacestd;intmain(){// let's generate some samples on the 3D plane of equation z = 2x+3y (with some noise)
DataMatrixsamples=DataMatrix::Random(12,2);VectorXfelevations=2*samples.col(0)+3*samples.col(1)+VectorXf::Random(12)*0.1;// and let's solve samples * [x y]^T = elevations in least square sense:
Matrix<float,2,1>xy=(samples.adjoint()*samples).llt().solve((samples.adjoint()*elevations));cout<<xy<<endl;}
automat=vec.asDiagonal();automat=vec.asDiagonal().toDenseMatrix();DiagonalMatrix<Scalar,SizeAtCompileTime>diag1(size);diag1.diagonal()=vector;vec1=mat1.diagonal();mat1.diagonal()=vec1;// main diagonal
vec1=mat1.diagonal(+n);mat1.diagonal(+n)=vec1;// n-th super diagonal
vec1=mat1.diagonal(-n);mat1.diagonal(-n)=vec1;// n-th sub diagonal
vec1=mat1.diagonal<1>();mat1.diagonal<1>()=vec1;// first super diagonal
vec1=mat1.diagonal<-2>();mat1.diagonal<-2>()=vec1;// second sub diagonal
mat3=scalar*diag1*mat1;mat3+=scalar*mat1*vec1.asDiagonal();mat3=vec1.asDiagonal().inverse()*mat1mat3=mat1*diag1.inverse()