Matlab移植到Eigen用到的词条
???????? 同型矩陣運算滿足加法交換律、結合律;并存在單位元、逆元、和0元,為同型矩陣對加法的交換環。
?????? ? Eigen的簡單運算參考:http://blog.163.com/jiaqiang_wang/blog/static/1188961532013625102721873/
一、For?Eigen
1.零初始化、單位陣、全1矩陣
//初始化狀態向量和狀態協方差 int initialize_x_and_p(Eigen::MatrixXf &x_k_k,Eigen::MatrixXf &p_k_k) {//Initial velocity valuesfloat v_0 = 0;float std_v_0 = 0.025;float w_0 = 1e-15;float std_w_0 = 0.025; // Initial state vector and covariance matrixx_k_k = Eigen::MatrixXf::Zero(1,13) ;x_k_k<<0,0,0,1,0,0,0,v_0,v_0,v_0,w_0,w_0,w_0;p_k_k= Eigen::MatrixXf::Zero(13,13);//eps為MATLAB的最小精度;eps是浮點相對誤差限,是指計算機用于區分兩個數的差的最小常數//最小精度eps(N)隨著數量級增大,eps也在逐漸增大p_k_k(1,1)=eps;p_k_k(2,2)=eps;p_k_k(3,3)=eps;p_k_k(4,4)=eps;p_k_k(5,5)=eps;p_k_k(6,6)=eps;p_k_k(7,7)=eps;p_k_k(8,8) =std_v_0 * std_v_0;p_k_k(9,9) =std_v_0 * std_v_0;p_k_k(10,10) =std_v_0 * std_v_0;p_k_k(11,11) =std_w_0 * std_w_0;p_k_k(12,12) =std_w_0 * std_w_0;p_k_k(13,13) =std_w_0 * std_w_0;return 1; }2.?矩陣元的運算
size():獲取矩陣的行數和列數
3.隨機矩陣生成
Matlab : M= rand( 1, nPointsRand )-0.5; //生成從0到1的nPointsRand個隨機數,再減去0.5即:(-0.5,.0.5)翻譯為Eigen:
4.矩陣復制及行列復制
<pre name="code" class="cpp"> int nPointsRand = 12;Eigen::MatrixXf X = Eigen::MatrixXf::Random(1,nPointsRand);Eigen::MatrixXf Y = Eigen::MatrixXf::Random(1,nPointsRand);Eigen::MatrixXf Z = Eigen::MatrixXf::Random(1,nPointsRand);Eigen::MatrixXf theta = Eigen::MatrixXf::Random(1,nPointsRand);Eigen::MatrixXf phi = Eigen::MatrixXf::Random(1,nPointsRand);Eigen::MatrixXf lambda = Eigen::MatrixXf::Random(1,nPointsRand);Eigen::MatrixXf randSphere6D =Eigen::MatrixXf (6,nPointsRand);//randSphere6D 是6*nPointsRandDouble!//以下兩種賦值方法都可以//randSphere6D(0)=X(0);//randSphere6D(1)=Y(0);//randSphere6D(2)=Z(0);//randSphere6D(3)= theta(0);//randSphere6D(4)= phi(0);//randSphere6D(5)=lambda(0);randSphere6D<< X,Y,Z,theta,phi,lambda;//釋放6個矩陣!X.resize(0,0);Y.resize(0,0);Z.resize(0,0);theta.resize(0,0);phi.resize(0,0);lambda.resize(0,0);
5.四舍五入、ceil、floor Matlab: round
6.三角函數
atan2(X,Y)的含義和atan(X/Y)的含義是一樣的。就是求正切值?X/Y?對應的弧度值。
但ATAN2(a, b) 與 ATAN(a/b)值域稍有不同,ATAN2(a,b)的取值范圍介于 -pi 到 pi 之間(不包括 -pi),而ATAN(a/b)的取值范圍介于-pi/2到pi/2之間(不包括±pi/2)。
atan2( hrl( 1, : ), hrl( 3, : ) )翻譯為Eigen://wishchin!
atan( hrl.row( 1)*hrl.row( 3)/(hrl.row(1).norm()*hrl.row( 3).norm() ) )
7.數組運算符,只是在矩陣運算符前面增加一點“.”來表示
SNIP........................8.矩陣整體運算
翻譯為:
Eigen: M.Array().inverse()// 值得注意的是:不能達到矩陣逆的實現 Eigen: M.inverse() //此函數可以實現,但有時會失效,這是為何?注意事項:
<pre name="code" class="cpp">#include <Eigen/Dense> Eigen: M.inverse() //包含此頭文件才能實現矩陣求逆。
9.多維重排
函數功能:在MATLAB、FreeMat中,該函數按指定的向量來重新排列一個數組。 語法格式: B = permute(A, order) ; 按照向量order指定的順序重排A的各維。B中元素和A中元素完全相同。但由于經過重新排列,在A、B訪問同一個元素使用的下標就不一樣了。order中的元素必須各不相同。
10.矩陣塊的獲取
Eigen: P.block(i, j, rows, cols) Matlab: P(i+1 : i+rows, j+1 : j+cols)實例:
Eigen::MatrixXf P_xv(13,13); //= P( 1:13, 1:13 ); P_xv=P.block(0,0,13,13); Eigen::MatrixXf P_yxv = P.block(13,0,P.rows()-13,13 );// P( 14:end, 1:13 ); Eigen::MatrixXf P_y = P.block(13,13,P.rows()-13,P.cols()-13 );//P( 14:end, 14:end ); Eigen::MatrixXf P_xvy = P.block(0,13,P.rows()-13,P.cols()-13 );//P( 1:13, 14:end );
11.關于Matlab?reshape
B = reshape(A,m,n) 返回一個m*n的矩陣B, B中元素是按列從A中得到的。如果A中元素個數沒有m*n個, 則會引發錯誤。
引用方法:列優先,逐個復制?到新的矩陣.......
12.Matlab?dot(A,B)和cross(A,B)
MATLAB中?dot(x,?y)和cross(x,?y)是向量內積和外積
Matlab:
cross(x,y)Eigen:
x.cross(y)? ?? Eigen還提供了dot()點乘函數和cross()叉乘函數。其中dot可以針對任意兩個長度相等的向量,而叉乘只能是兩個三維向量,例如Vector3d v(1, 2, 3); Vector3d w(0, 1, 2); 那么v.dot(w) 得到的結果是8(等價于v.adjoint() * w),v.corss(w)得到的結果是(1;-2;1)。
13.對于這種形式:X_km1_k = [ Xv_km1_k; X_k( 14:end,: ) ];
直接對新矩陣進行添加...
14.Matlab sparse
Matlab里面有兩個非常有用函數:randperm()與sparse()。
randperm(n)會返回一個1維數組(向量),該數組是整數1到n的一組隨機排列,彼此無重復,順序隨機。
sparse(X)會返回一個矩陣X的稀疏矩陣的表達形式。在Matlab的Workspace中,稀疏矩陣的圖標是,不同于一般的結構體、矩陣等。
15.Matlab?eig函數
Matlab里面的eig(M)函數給出了求特征值的方法:
M = eig(S);
翻譯成Eigen為:
Eigen::MatrixXf S = features_info[i_feature].S;Eigen::SelfAdjointEigenSolver<Eigen::MatrixXf> eigensolver(S);Eigen::MatrixXf E = eigensolver.eigenvalues()
16.相關系數 corrcoef
Matlab相關系數的意義:
Eigen::MatrixXf correlation_matrix = corrcoef( LocM );對行向量求相關系數 , 與列數無關,返回?cols()*cols()?矩陣...
翻譯成Eigen:
還是自己寫個函數吧
//1.求協方差
Eigen::MatrixXf CIcSearchM::cov(Eigen::MatrixXf &d1, Eigen::MatrixXf &d2) {Eigen::MatrixXf? CovM(1,1);assert(1 ==d1.cols() && 1 ==d2.cols() &&d1.cols()==d2.cols()? );//求協方差float Ex =0;float Ey=0;for (int i=0;i< d1.rows();++i){Ex +=d1(i);Ey +=d2(i);}Ex /=d1.rows();Ey /=d2.rows();for (int i=0;i< d1.rows();++i){CovM(0) += (d1(i)-Ex)*(d2(i)-Ey);}CovM(0) /= d1.rows() -1;return CovM; }//2.寫入方差矩陣
//求矩陣的相關系數! //返回矩陣A的列向量的相關系數矩陣//對行向量求相關系數 , 與行數無關,返回 cols()*cols() 矩陣... Eigen::MatrixXf CIcSearchM::corrcoef(Eigen::MatrixXf &M) {// C(i,j)/SQRT(C(i,i)*C(j,j)).//C is the covariation Matrixint Row= M.rows();int Col= M.cols();int Order= Col;//int Order= (std::max)(Row,Col);Eigen::MatrixXf Coef(Order,Order);for (int i=0;i<Order;++i){for (int j=0;j<Order;++j){Coef(i,j)= cov((Eigen::MatrixXf)M.col(i),(Eigen::MatrixXf)M.col(j))(0);}}return Coef; }
17.Matlab?logical函數
Matlab?logical:把非0元素轉化為整數/bool型數1
M =0.4300 -0.0300 -0.0400 -0.1600 -0.2500 -0.6500 -0.6700-0.0300 0.0400 0.1600 0.2500 0.6500 0.6700 0.2500>> x =logical(M) x =1 1 1 1 1 1 11 1 1 1 1 1 1>> M(2,2)=0 M =0.4300 -0.0300 -0.0400 -0.1600 -0.2500 -0.6500 -0.6700-0.0300 0 0.1600 0.2500 0.6500 0.6700 0.2500 <pre name="code" class="cpp">>> x =logical(M) x =1 1 1 1 1 1 11 0 1 1 1 1 1 轉化為Eigen://代替Matlab的邏輯轉換函數!把非0值轉換為1,0值為0! Eigen::MatrixXf CRansHyper::logical(Eigen::MatrixXf &M) {Eigen::MatrixXf MD(M.rows(),M.cols());for (int i=0;i<M.rows();++i){for (int j=0;j< M.cols();++j){if (M(i,j)!=0 ){MD(i,j) =1;}elseMD(i,j) =0;}}return MD; }
18.Matlab repmat函數
repmat 重復填充一個小矩陣形成一個大矩陣
>> M=[45,6,6;6,7,8] M =45 6 66 7 8>> N =repmat(M,2,3) N =45 6 6 45 6 6 45 6 66 7 8 6 7 8 6 7 845 6 6 45 6 6 45 6 66 7 8 6 7 8 6 7 8釋義:把矩陣M(2,3)以兩行三列的形式填充成大矩陣N(4,9)
轉換成Eigen:
//用小矩陣填充成大矩陣!wishchin!! Eigen::MatrixXf CRansHyper::repmat(Eigen::MatrixXf &M,int rowM,int colM) {Eigen::MatrixXf MD(rowM*M.rows(), colM*M.cols() );for (int i=0;i< rowM;++i){for (int j=0;j< colM;++j){for (int m=0;m< M.rows();++m){for (int n=0;n<M.cols();++n){MD(i*M.rows()+m, j*M.cols()+n)= M(m,n);}}}}return MD; }
19.Matlab?三角函數
matlab三角函數對數組求值相當于對每一個元素求值再填入矩陣
K>> x=[5,34,5,6] x =5 34 5 6 K>> sin(x) ans =-0.9589 0.5291 -0.9589 -0.2794 K>> sin(5) ans =-0.9589
20.Matlab? find函數
matlab: 語法:
/* 找出矩陣X中的所有非零元素,并將這些元素的線性索引值(linear indices:按列)返回到向量ind中。如果X是一個行向量,則ind是一個行向量;否則,ind是一個列向量。如果X不含非零元素或是一個空矩陣,則ind是一個空矩陣。 */ind = find(X)/* 返回第一個非零元素k的索引值。 k必須是一個正數,但是它可以是任何數字數值類型。 */ind = find(X, k)/* 返回X中非零元素行索引值的向量*/ind = find(X, k, 'first') /* 返回最后一個非零元素k的索引值。*/ind = find(X, k, 'last')/* 返回矩陣X中非零元素的行和列的索引值。這個語法對于處理稀疏矩陣尤其有用。如果X是一個N(N>2)維矩陣,col包括列的線性索引。例如,一個5*7*3的矩陣X,有一個非零元素X(4,2,3),find函數將返回row=4和col=16。也就是說,(第1頁有7列)+(第2頁有7列)+(第3頁有2列)=16。*/[row,col] = find(X, ...)/* 返回X中非零元素的一個列或行向量v,同時返回行和列的索引值。如果X是一個邏輯表示,則v是一個邏輯矩陣。輸出向量v(稀疏矩陣)包含通過評估X表示得到的邏輯矩陣的非零元素。*/[row,col,v] = find(X, ...)
改寫其中的一個:
/* 找出矩陣X中的所有非零元素,并將這些元素的線性索引值(linear indices:按列)返回到向量中。 如果X是一個行向量,則ind是一個行向量;否則,ind是一個列向量。 如果X不含非零元素或是一個空矩陣,則ind是一個空矩陣。 *///默認返回大于0的值//為X *1的矩陣,行優先! Eigen::MatrixXf CEkfSlam::find(Eigen::MatrixXf &M) {assert(1 == M.rows() );int counter =0;//返回數組中大于value的下標,返回索引//使用Push太慢了,還是遍歷兩次吧for (int i =0;i< M.cols();++i){if (M(i)> 1){++counter;}}Eigen::MatrixXf index(counter,1);counter=0;for (int i =0;i< M.cols();++i){if (M(i)> 1){M(counter) =counter;++counter;}}return index; }
二、For? OpenCV—Mat
1. 三角函數
atan2(X,Y)的含義和atan(X/Y)的含義是一樣的。就是求正切值?X/Y?對應的弧度值。
但ATAN2(a, b) 與 ATAN(a/b)值域稍有不同,ATAN2(a,b)的取值范圍介于 -pi 到 pi 之間(不包括 -pi),而ATAN(a/b)的取值范圍介于-pi/2到pi/2之間(不包括±pi/2)。
atan2( hrl( 1, : ), hrl( 3, : ) )
2.圖像塊獲取
Matlab可以直接使用:和索引獲取矩陣塊,
翻譯成OpenCV:
//使用OpenCV getRect函數 //GetRectSubPix 從圖像中提取象素矩形,使用子象素精度 std::vector<CvPoint> cs(0); cv::Mat RectImg; const double Thres =100; CvSize Rect; Rect.height=initializing_box_semisize.height; Rect.width =initializing_box_semisize.width ; cv::getRectSubPix(im_k,Rect,search_region_center,RectImg,-1);
3.Matlab到OpenCV?Mat型的轉化
???? OpenCV的Mat型提供了各種矩陣運算,其中一部分如下
static Matx all(_Tp alpha);static Matx zeros();static Matx ones();static Matx eye();static Matx <span style="color:#FF0000;">diag</span>(const diag_type& d);static Matx randu(_Tp a, _Tp b);static Matx randn(_Tp a, _Tp b);//! dot product computed with the default precision_Tp dot(const Matx<_Tp, m, n>& v) const;//! dot product computed in double-precision arithmeticsdouble ddot(const Matx<_Tp, m, n>& v) const;//! conversion to another data typetemplate<typename T2> operator Matx<T2, m, n>() const;//! change the matrix shapetemplate<int m1, int n1> Matx<_Tp, m1, n1> reshape</span>() const;//! extract part of the matrixtemplate<int m1, int n1> Matx<_Tp, m1, n1> get_minor(int i, int j) const;//! extract the matrix rowMatx<_Tp, 1, n> row(int i) const;//! extract the matrix columnMatx<_Tp, m, 1> col(int i) const;//! extract the matrix diagonaldiag_type diag() const;//! transpose the matrixMatx<_Tp, n, m> t() const;//! invert matrix the matrixMatx<_Tp, n, m> inv (int method=DECOMP_LU) const;//! solve linear systemtemplate<int l> Matx<_Tp, n, l> solve(const Matx<_Tp, m, l>& rhs, int flags=DECOMP_LU) const;Vec<_Tp, n> solve(const Vec<_Tp, m>& rhs, int method) const;//! multiply two matrices element-wiseMatx<_Tp, m, n> mul(const Matx<_Tp, m, n>& a) const;Vec cross(const Vec& v) const;
三、for C++
1.關于運算符重載
??????? 要把需要重載的運算符的函數體,寫在CPP文件里。
2.生成隨機數
Y = rand(n) Y = rand(m,n) Y = rand([m n]) Y = rand(m,n,p,...) Y = rand([m n p...]) Y = rand(size(A)) rands = rand('state')
描述:
rand函數產生由在(0, 1)之間均勻分布的隨機數組成的數組。
Y = rand(n) 返回一個n x n的隨機矩陣。如果n不是數量,則返回錯誤信息。 Y = rand(m,n) 或 Y = rand([m n]) 返回一個m x n的隨機矩陣。 Y = rand(m,n,p,...) 或 Y = rand([m n p...]) 產生隨機數組。 Y = rand(size(A)) 返回一個和A有相同尺寸的隨機矩陣。
翻譯成C++:
v1 = rand() % 100; // v1 in the range 0 to 99v2 = rand() % 100 + 1; // v2 in the range 1 to 100v3 = rand() % 30 + 1985; // v3 in the range 1985-2014
3.Matlab meshgrid
對于數據:
uv_predSrc:
47.9999999999998 48.9999999999998 49.9999999999998 50.9999999999998 51.9999999999998 52.9999999999998 53.9999999999998為 1*7 的矩陣
經過轉換:
獲取的結果為:
u_pred:
v_pred: 47.9999999999998 47.9999999999998 47.9999999999998 47.9999999999998 47.9999999999998 47.9999999999998 47.9999999999998 48.9999999999998 48.9999999999998 48.9999999999998 48.9999999999998 48.9999999999998 48.9999999999998 48.9999999999998 49.9999999999998 49.9999999999998 49.9999999999998 49.9999999999998 49.9999999999998 49.9999999999998 49.9999999999998 50.9999999999998 50.9999999999998 50.9999999999998 50.9999999999998 50.9999999999998 50.9999999999998 50.9999999999998 51.9999999999998 51.9999999999998 51.9999999999998 51.9999999999998 51.9999999999998 51.9999999999998 51.9999999999998 52.9999999999998 52.9999999999998 52.9999999999998 52.9999999999998 52.9999999999998 52.9999999999998 52.9999999999998 53.9999999999998 53.9999999999998 53.9999999999998 53.9999999999998 53.9999999999998 53.9999999999998 53.9999999999998
程序功能為:
??????? 把一系列下標轉化為兩個下標方陣,前一個為行復制,后一個為列復制。
轉換為C++寫一個循環就可以了.
4.Matlab interp2
四、for? OpenGL
1.畫出射線
Matlab:
function vectarrow(p0,p1,color)if max(size(p0))==3if max(size(p1))==3x0 = p0(1);y0 = p0(2);z0 = p0(3);x1 = p1(1);y1 = p1(2);z1 = p1(3);plot3([x0;x1],[y0;y1],[z0;z1],'color',color);?? % Draw a line between p0 and p1 ?畫出從p0到p1的射線
轉換為OpenGL:
一大堆代碼:
</pre><pre name="code" class="cpp">this->vectArrow(PointS,PointE,ColorType);int CPlot::vectArrow(Eigen::MatrixXf &PointS, Eigen::MatrixXf &PointE,std::string type) {Eigen::MatrixXf EndPoints(6,1);EndPoints<<PointS(0),PointS(1),PointS(2),PointE(0),PointE(1),PointE(2);this->openglViewer->GetVectorPoint(EndPoints);//return 1; }drawTransAxis(this->m_PointSeries); int OpenGLViewer::GetVectorPoint(Eigen::MatrixXf &endPoints){Eigen::MatrixXf NewEndPoint= endPoints;this->m_PointSeries.push_back( NewEndPoint);return 1;}void OpenGLViewer::paintGL(){glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);this->drawWorldAxis();this->drawTransAxis(this->m_PointSeries);this->drawTriangle(this->m_TriangleSeries);this->drawCloud(); } void OpenGLViewer::drawTransAxis(std::vector<Eigen::MatrixXf> &PointSeries) {GLfloat x = GLfloat(640) / 480;glMatrixMode(GL_MODELVIEW); glLoadIdentity();gluLookAt(-2.0 , 6.0, -4.0, 0.0 , 0.0 , 0.0 , 0.0, 1.0 , 0.0);float len = 0.2;glTranslatef(transX,transY,-transZ);glRotatef(rotationX , 1.0,0.0,0.0);glRotatef(rotationY , 0.0,1.0,0.0);glRotatef(rotationZ , 0.0,0.0,1.0);glScalef(xscale, yscale, zscale);//The Cube aixs / coordinate system!//1. The axis line! glColor3f(1.0f,1.0f,1.0f); glBegin(GL_LINES); glVertex3f(-1.9f,00.0f,0.0f); glVertex3f(1.9f,0.0f,0.0f); glVertex3f(0.0f,-1.9f,0.0f); glVertex3f(0.0f,1.9f,0.0f); glVertex3f(0.0f,0.0f,-1.9f); glVertex3f(0.0f,0.0f,1.9f); //畫出多個線段 for (int i=0;i< PointSeries.size();++i){glVertex3f(PointSeries[i](0),PointSeries[i](1),PointSeries[i](2) ); glVertex3f(PointSeries[i](3),PointSeries[i](4),PointSeries[i](5) ); }glEnd(); //The Cube aixs / coordinate system!//2. The axis arrow!glColor3f(1.0f,0.0f,0.0f); //x arrowglPushMatrix(); glTranslatef(1.2f,0.0f,0.0f); glRotatef(90.0f,0.0f,1.0f,0.0f); glutSolidCone(0.05,0.15,10,10); glPopMatrix(); glColor3f(0.0f,1.0f,0.0f); // y glPushMatrix(); glTranslatef(0.0f,1.2f,0.0f); glRotatef(-90.0f,1.0f,0.0f,0.0f); glutSolidCone(0.05,0.15,10,10); glPopMatrix(); glColor3f(0.0f,0.0f,1.0f); // z glPushMatrix(); glTranslatef(0.0f,0.0f,1.2f); glRotatef(90.0f,0.0f,0.0f,1.0f); glutSolidCone(0.05,0.15,10,10); glPopMatrix(); glFlush(); }五、常見錯誤集合
1. 錯誤?? ?52?? ?error C2338: THIS_METHOD_IS_ONLY_FOR_VECTORS_OF_A_SPECIFIC_SIZE?? ?c:\tools\eigen\include\eigen\src\core\matrix.h?? ?265
引發錯誤的代碼段:
(1,x_k_km1.rows()-13,x_k_km1.cols() )修改為: (x_k_km1.rows()-13,x_k_km1.cols() )就可以了!
總結
以上是生活随笔為你收集整理的Matlab移植到Eigen用到的词条的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 使用Visio—UML画类图
- 下一篇: 三国志战略版斯巴达什么意思 三国演义第1