zoukankan      html  css  js  c++  java
  • Eigen矩阵基本运算

    1 矩阵基本运算简介

    Eigen重载了+,-,*运算符。同时提供了一些方法如dot(),cross()等。对于矩阵类的运算符重载只支持线性运算,比如matrix1*matrix2是矩阵相乘,当然必须要满足矩阵乘法规则。对于向量和标量的加法(vector+scalar)这里并不支持,关于非线性运算这里暂不介绍。

    2 加减运算

    矩阵加减运算中必须要保证左右矩阵的行列对应相等。此外更重要的一点是,矩阵的类型也必须一致,这里的矩阵运算并不支持隐式的类型转换。矩阵运算中重载的运算符有:

    1. 二元运算符+:a+b
    2. 二元运算符-:a-b
    3. 一元运算符-:-a
    4. 复合运算符+=:a+=b
    5. 复合运算符-=:a-=b

    下面是使用示例:

    #include <iostream>
    #include "EigenDense"
    
    using namespace Eigen;
    
    int main()
    {
    	Matrix2d a;
    	a<<1,2,
    	   3,4;
    	MatrixXd b(2,2);
    	b<<2,3,
    	   1,4;
    	std::cout<<"a+b=
    "<<a+b<<std::endl;
    	std::cout<<"a-b=
    "<<a-b<<std::endl;
    	std::cout<<"Doing a+=b;"<<std::endl;
    	a+=b;
    	std::cout<<"Now a=
    "<<a<<std::endl;
    	Vector3d v(1,2,3);
    	Vector3d w(1,0,0);
    	std::cout<<"-v+w-v=
    "<<-v+w-v<<std::endl;
    }
    

    执行结果如下:

    a+b=
    3 5
    4 8
    a-b=
    -1 -1
     2  0
    Doing a+=b;
    Now a=
    3 5
    4 8
    -v+w-v=
    -1
    -4
    -6
    
    

    3 和标量的乘法和除法

    对于矩阵和标量的乘法和除法也非常简单,重载的操作符如下:

    1. 二元运算符:matrixscalar
    2. 二元运算符:scalarmatrix
    3. 二元运算符/:matrix/scalar
    4. 复合运算符=:matrix=scalar
    5. 复合运算符/=:matrix/=scalar

    下面是使用示例:

    #include <iostream>
    #include "EigenDense"
    
    using namespace Eigen;
    
    int main()
    {
    	Matrix2d a;
    	a<<1,2,
    	   3,4;
    	Vector3d v(1,2,3);
    	std::cout<<"a*2.5=
    "<<a*2.5<<std::endl;
    	std::cout<<"0.1*v=
    "<<0.1*v<<std::endl;
    	std::cout<<"Doing v*=2;"<<std::endl;
    	v*=2;
    	std::cout<<"Now v=
    "<<v<<std::endl;
    }
    

    执行结果如下:

    a*2.5=
    2.5   5
    7.5  10
    0.1*v=
    0.1
    0.2
    0.3
    Doing v*=2;
    Now v=
    2
    4
    6
    

    4 表达式计算优化原则

    关于矩阵表达式的计算这里有一点需要说明。在Eigen中,算数运算操作(比如+)并不会立即对表达式两端进行求值,而仅仅只是返回一个“表达式”,这个表达式对计算的结果的表现进行简单的描述,而真正的计算会等到最后才会进行。一般来说会等到操作运算符=执行时进行计算。这个机制会极大的优化矩阵的计算性能。请看下面的这个例子:

    VectorXf a(50),b(50),c(50),d(50);
    ...
    a=3*b+4*c+5*d;
    

    虽然上面这个表达式中有多个运算符,但并不会使用多个循环对每个运算符左右两边的矩阵进行求值。而是简化为下面这一个循环。

    for(int i = 0;i < 50;++i)
      a[i] = 3*b[i] + 4*c[i] + 5*d[i];
    

    所以我们并不用担心较大或者复杂的运算表达式会降低我们的运算效率。它只会给Eigen提供更多的优化机会。

    5 转置(Transposition)和共轭(conjugation)

    对于矩阵的转置(transpose)

    ,共轭(conjugate)

    以及伴随矩阵(adjoint--conjugate transose)a*可以使用transpose(),conjugate(),'adjoint()'函数求得。

    #include <iostream>
    #include "EigenDense"
    
    using namespace Eigen;
    
    int main()
    {
    	MatrixXcf a = MatrixXcf::Random(2,2);
    	std::cout<<"Matrix a=
    "<<a<<std::endl;
    	std::cout<<"Here is the matrix a^T
    "<<a.transpose()<<std::endl;
    	std::cout<<"Here is the conjugate of a
    "<<a.conjugate()<<std::endl;
    	std::cout<<"Here is the matrix a^*
    "<<a.adjoint()<<std::endl;
    }
    

    执行结果如下:

    Matrix a=
     (0.127171,-0.997497) (-0.0402539,0.170019)
     (0.617481,-0.613392)  (0.791925,-0.299417)
    Here is the matrix a^T
     (0.127171,-0.997497)  (0.617481,-0.613392)
    (-0.0402539,0.170019)  (0.791925,-0.299417)
    Here is the conjugate of a
       (0.127171,0.997497) (-0.0402539,-0.170019)
       (0.617481,0.613392)    (0.791925,0.299417)
    Here is the matrix a^*
       (0.127171,0.997497)    (0.617481,0.613392)
    (-0.0402539,-0.170019)    (0.791925,0.299417)
    

    对于实数矩阵,conjugate()不会有任何动作。所以adjoint()=transpose().

    需要说明的是,作为基本运算符transpose()和adjoint()会简单的返回一个没有做任何转换的代理对象(proxy object).如果使用b=a.transpose(),会使结果转换和写入b同时进行。然后这种转换和写入同时也会引起如下问题。如果我们执行a=a.transpose(),由于在转换前就开始写入了,所以并不会将转换后的结果写入a中。

    #include <iostream>
    #include "EigenDense"
    
    using namespace Eigen;
    using namespace std;
    
    int main()
    {
    	Matrix2i a;
    	a<<1,2,3,4;
    	cout<<"Here is the matrix a:
    "<<endl;
    	a=a.transpose();	//!!! do NOT do this!!!
    	cout<<"and the result of the aliasing effect:
    "<<a<<endl;
    }
    

    官方给的例程说执行上面的程序会发现转换后a的矩阵等于转换前的,但是我测试的结果是程序直接出错并停止运行。
    如果我们想对a本身进行转换可使用transposeInPlace()函数。同样的如果求伴随矩阵的话可使用adjoinInPlace()函数。

    #include <iostream>
    #include "EigenDense"
    
    using namespace Eigen;
    using namespace std;
    
    int main()
    {
    	MatrixXf a(2,3);
    	a<<1,2,3,
    	   4,5,6;
    	cout<<"Here is the initial matrix a:
    "<<a<<endl;
    	a.transposeInPlace();
    	cout<<"and after being transposed:
    "<<a<<endl;
    	a.adjointInPlace();
    	cout<<"and (a^T)^*=
    "<<a<<endl;
    }
    

    执行结果如下:

    Here is the initial matrix a:
    1 2 3
    4 5 6
    and after being transposed:
    1 4
    2 5
    3 6
    and (a^T)^*=
    1 2 3
    4 5 6
    

    6 矩阵-矩阵以及矩阵-向量相乘

    由于向量属于特殊的矩阵,所以我们只需考虑矩阵的相乘即可。矩阵和矩阵相乘可以使用如下两种运算符:

    1. 二元运算符:ab
    2. 复合运算符=:a=b

    下面是使用示例:

    #include <iostream>
    #include "EigenDense"
    
    using namespace Eigen;
    using namespace std;
    
    int main()
    {
    	Matrix2d mat;
    	mat<<1,2,
    		 3,4;
    	Vector2d u(1,-1),v(2,0);
    	
    	cout<<"Here is mat*mat:
    "<<mat*mat<<endl;
    	cout<<"Here is mat*u:
    "<<mat*u<<endl;
    	cout<<"Here is u^T*mat:
    "<<u.transpose()*mat<<endl;
    	cout<<"Here is u^T*v:
    "<<u.transpose()*v<<endl;
    	cout<<"Here is u*v^T:
    "<<u*v.transpose()<<endl;
    	cout<<"Let's multiply mat by itsef"<<endl;
    	mat = mat*mat;
    	cout<<"Now mat is mat:
    "<<mat<<endl;
    }
    

    执行结果如下:

    Here is mat*mat:
     7 10
    15 22
    Here is mat*u:
    -1
    -1
    Here is u^T*mat:
    -2 -2
    Here is u^T*v:
    2
    Here is u*v^T:
     2  0
    -2 -0
    Let's multiply mat by itsef
    Now mat is mat:
     7 10
    15 22
    
    

    在矩阵的乘法中我们不用担心a=a*a会引起上面的使用别名问题(aliasing issues),因为这里会自动的引入一个中间变量因此a=a*a相当于temp=a*a;a=temp.如果你知道你的计算不会引起使用别名问题,那么你可以使用noalias()函数去避免使用这个中间变量以增加运算速度。如c.noalias()+=a*b;.关于使用别名的问题可以在官网aliasing中查看更多信息。
    对于BLAS用户可能担心运算性能的问题,但正如我们前面所说的c.noalias-=2*a.adjoint()*b会完全的进行优化只触发一个函数调用。

    7 点乘和叉乘

    对于內积和外积的计算可以使用dot()cross()函数。当然点乘会得到一个1×1的矩阵(u.adjoint()*v)。

    下面是一个使用示例:

    #include <iostream>
    #include "EigenDense"
    
    using namespace Eigen;
    using namespace std;
    
    int main()
    {
    	Vector3d v(1,2,3);
    	Vector3d w(0,1,2);
    	
    	cout<<"DOt product:"<<v.dot(w)<<endl;
    	double dp = v.adjoint()*w;	//automatic conversion of the inner product to a scalar
    	cout<<"Dot product via a matrix product: "<<dp<<endl;
    	cout<<"Cross product:
    "<<v.cross(w)<<endl;
    }
    

    计算结果如下所示:

    DOt product:8
    Dot product via a matrix product: 8
    Cross product:
     1
    -2
     1
    

    需要记住叉积只能对3维向量使用,而点积可以对任意维的向量使用。对于复数,点积会对第一个向量首先进行共轭然后在和第二个向量相乘。

    8 其他一些基本运算

    Eigen同样提供了其他的函数对矩阵的所有元素进行操作,比如sum(对矩阵所有元素求和),product(全部元素相乘),maximum(求最大值)和minimum(求最小值)。

    下面是一个示例:

    #include <iostream>
    #include "EigenDense"
    
    using namespace Eigen;
    using namespace std;
    
    int main()
    {
    	Matrix2d mat;
    	mat<<1,2,
    		 3,4;
    	cout<<"Here is mat.sum():		"<<mat.sum()<<endl;
    	cout<<"Here is mat.prd():		"<<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;
    }
    

    执行结果如下:

    Here is mat.sum():              10
    Here is mat.prd():              24
    Here is mat.mean():             2.5
    Here is mat.minCoeff():         1
    Here is mat.maxCoeff():         4
    Here is mat.trace():            5
    

    对于求矩阵的迹除了使用trace()还可以使用高效的a.diagonal().sum()

    对于求minCoeffmaxCoeff除了能求出最大值以外还能获取相关的索引下标。

    #include <iostream>
    #include <cstddef>
    #include "EigenDense"
    
    using namespace Eigen;
    using namespace std;
    
    int main()
    {
    	Matrix3f m = Matrix3f::Random();
    	ptrdiff_t i,j;
    	float minOfM = m.minCoeff(&i,&j);
    	cout<<"Here is the matrix m:
    "<<m<<endl;
    	cout<<"Its minimum coefficient ("<<minOfM
    		<<") is at position ("<<i<<","<<j<<")"<<endl<<endl;
    	RowVector4i v = RowVector4i::Random();
    	int maxOfv=v.maxCoeff(&i);
    	cout<<"Here is the vector v: "<<v<<endl;
    	cout<<"Its maximun coefficient ("<<maxOfv
    		<<") is at position "<<i<<endl;
    }
    

    执行结果如下:

    Here is the matrix m:
     -0.997497   0.617481  -0.299417
      0.127171   0.170019   0.791925
     -0.613392 -0.0402539    0.64568
    Its minimum coefficient (-0.997497) is at position (0,0)
    
    Here is the vector v:   8080 -10679  11761   6897
    Its maximun coefficient (11761) is at position 2
    

    9 有效性检查

    Eigen会进行操作的有效性检测。如果可能的话在编译阶段就会给出相关的错误信息,虽然这些信息看起来又臭又长。但是Eigen会将重要的信息使用大写加下划线的形式写出。比如:

    Matrix3f m;
    Vector4f v;
    v=m*v;  //Compile-time error:YOU_MIXED_MATRICES_OF_DIFFERENT_SIZES
    

    当然对于大多数情况,比如检查动态数组大写。编译器并不能在编译阶段检查出错误。Eigen在运行中会使用断言(assertions)进行检测。这意味着,如果我们使用了"debug mode",那么程序在检测到一个非法操作后会被错误信息打断。如果没有使用断言机制,那么程序可能会遇到灾难性的错误。

    MatrixXf m(3,3);
    VectorXf v(4);
    v = m*v;  //Run-time assertion failure here:"invalid matrix product"
    
  • 相关阅读:
    使用NBU进行oracle异机恢复
    mycat偶尔会出现JVM报错double free or corruption并崩溃退出
    exp导出数据时丢表
    service_names配置不正确,导致dg创建失败
    XML概念定义以及如何定义xml文件编写约束条件java解析xml DTD XML Schema JAXP java xml解析 dom4j 解析 xpath dom sax
    HTTP协议简介详解 HTTP协议发展 原理 请求方法 响应状态码 请求头 请求首部 java模拟浏览器客户端服务端
    java集合框架容器 java框架层级 继承图结构 集合框架的抽象类 集合框架主要实现类
    【JAVA集合框架一 】java集合框架官方介绍 Collections Framework Overview 集合框架总览 翻译 javase8 集合官方文档中文版
    java内部类深入详解 内部类的分类 特点 定义方式 使用
    再谈包访问权限 子类为何不能使用父类protected方法
  • 原文地址:https://www.cnblogs.com/yabin/p/6442922.html
Copyright © 2011-2022 走看看