Eigen 學習之塊操作

Eigen 爲 Matrix 、Array 和 Vector提供了塊操作方法。塊區域可以被用作 左值 和 右值。在Eigen中最常用的塊操作函數是 .block() 。

block() 方法的定義如下:

block of size (p,q) ,starting at (i,j)。matrix.block(i,j,p,q); matrix.block<p,q>(i,j);

上述兩種形式都可以被用在固定大小和動態大小的矩陣中。

舉例如下:

#include <iostream>
#include <eigen3/Eigen/Dense>

using namespace Eigen;
using namespace std;

int main(int argc ,char** argv)
{
    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,2>(1,1)<<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;
    }
    return 0;
}

block也可以被用作左值,即block可以進行賦值操作。


#include <iostream>
#include <eigen3/Eigen/Dense>

using namespace Eigen;
using namespace std;

int main(int argc ,char** argv)
{
    Array22f m;
    m << 1,2,
         3,4;

    Array44f a = Array44f::Constant(0.6);
    cout<<"Here is the array a"<<endl<<a<<endl<<endl;
    a.block<2,2>(1,1) = m;
    cout<<"Here is now a with m copoed into its central 2x2 block"<<endl<<a<<endl<<endl;
    a.block(0,0,2,3) = a.block(2,1,2,3);
    cout<<"Here is now a with bottom-right 2x3 copied into top-left 2x3 block:"<<endl<<a<<endl<<endl;
    return 0;
}

特殊情況下的塊操作,比如取整行或者整列,取上面的若干行或者底部的若干行。

取 整行和整列的操作如下:

matrix.row(i);

  matrix.col(j);

訪問矩陣的行和列的操作如下:

#include <iostream>
#include <eigen3/Eigen/Dense>

using namespace Eigen;
using namespace std;

int main(int argc ,char** argv)
{
    MatrixXf m(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 4 times the first column into the third column,the matrix m is:\n";
    cout<<m<<endl;
    return 0;
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章