Eigen矩阵基本运算
1 矩阵基本运算简介
Eigen重载了+,-,*运算符。同时提供了一些方法如dot(),cross()等。对于矩阵类的运算符重载只支持线性运算,比如matrix1*matrix2是矩阵相乘,当然必须要满足矩阵乘法规则。对于向量和标量的加法(vector+scalar)这里并不支持,关于非线性运算这里暂不介绍。
2 加减运算
矩阵加减运算中必须要保证左右矩阵的行列对应相等。此外更重要的一点是,矩阵的类型也必须一致,这里的矩阵运算并不支持隐式的类型转换。矩阵运算中重载的运算符有:
- 二元运算符+:a+b
- 二元运算符-:a-b
- 一元运算符-:-a
- 复合运算符+=:a+=b
- 复合运算符-=:a-=b
下面是使用示例:
#include <iostream>
#include "Eigen\Dense"
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=\n"<<a+b<<std::endl;
std::cout<<"a-b=\n"<<a-b<<std::endl;
std::cout<<"Doing a+=b;"<<std::endl;
a+=b;
std::cout<<"Now a=\n"<<a<<std::endl;
Vector3d v(1,2,3);
Vector3d w(1,0,0);
std::cout<<"-v+w-v=\n"<<-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 和标量的乘法和除法
对于矩阵和标量的乘法和除法也非常简单,重载的操作符如下:
- 二元运算符:matrixscalar
- 二元运算符:scalarmatrix
- 二元运算符/:matrix/scalar
- 复合运算符=:matrix=scalar
- 复合运算符/=:matrix/=scalar
下面是使用示例:
#include <iostream>
#include "Eigen\Dense"
using namespace Eigen;
int main()
{
Matrix2d a;
a<<1,2,
3,4;
Vector3d v(1,2,3);
std::cout<<"a*2.5=\n"<<a*2.5<<std::endl;
std::cout<<"0.1*v=\n"<<0.1*v<<std::endl;
std::cout<<"Doing v*=2;"<<std::endl;
v*=2;
std::cout<<"Now v=\n"<<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 "Eigen\Dense"
using namespace Eigen;
int main()
{
MatrixXcf a = MatrixXcf::Random(2,2);
std::cout<<"Matrix a=\n"<<a<<std::endl;
std::cout<<"Here is the matrix a^T\n"<<a.transpose()<<std::endl;
std::cout<<"Here is the conjugate of a\n"<<a.conjugate()<<std::endl;
std::cout<<"Here is the matrix a^*\n"<<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 "Eigen\Dense"
using namespace Eigen;
using namespace std;
int main()
{
Matrix2i a;
a<<1,2,3,4;
cout<<"Here is the matrix a:\n"<<endl;
a=a.transpose(); //!!! do NOT do this!!!
cout<<"and the result of the aliasing effect:\n"<<a<<endl;
}
官方给的例程说执行上面的程序会发现转换后a的矩阵等于转换前的,但是我测试的结果是程序直接出错并停止运行。
如果我们想对a本身进行转换可使用transposeInPlace()函数。同样的如果求伴随矩阵的话可使用adjoinInPlace()函数。
#include <iostream>
#include "Eigen\Dense"
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:\n"<<a<<endl;
a.transposeInPlace();
cout<<"and after being transposed:\n"<<a<<endl;
a.adjointInPlace();
cout<<"and (a^T)^*=\n"<<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 矩阵-矩阵以及矩阵-向量相乘
由于向量属于特殊的矩阵,所以我们只需考虑矩阵的相乘即可。矩阵和矩阵相乘可以使用如下两种运算符:
- 二元运算符:ab
- 复合运算符=:a=b
下面是使用示例:
#include <iostream>
#include "Eigen\Dense"
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:\n"<<mat*mat<<endl;
cout<<"Here is mat*u:\n"<<mat*u<<endl;
cout<<"Here is u^T*mat:\n"<<u.transpose()*mat<<endl;
cout<<"Here is u^T*v:\n"<<u.transpose()*v<<endl;
cout<<"Here is u*v^T:\n"<<u*v.transpose()<<endl;
cout<<"Let's multiply mat by itsef"<<endl;
mat = mat*mat;
cout<<"Now mat is mat:\n"<<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 "Eigen\Dense"
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:\n"<<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 "Eigen\Dense"
using namespace Eigen;
using namespace std;
int main()
{
Matrix2d mat;
mat<<1,2,
3,4;
cout<<"Here is mat.sum():\t\t"<<mat.sum()<<endl;
cout<<"Here is mat.prd():\t\t"<<mat.prod()<<endl;
cout<<"Here is mat.mean():\t\t"<<mat.mean()<<endl;
cout<<"Here is mat.minCoeff():\t\t"<<mat.minCoeff()<<endl;
cout<<"Here is mat.maxCoeff():\t\t"<<mat.maxCoeff()<<endl;
cout<<"Here is mat.trace():\t\t"<<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()。
对于求minCoeff和maxCoeff除了能求出最大值以外还能获取相关的索引下标。
#include <iostream>
#include <cstddef>
#include "Eigen\Dense"
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:\n"<<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"
Eigen矩阵基本运算的更多相关文章
- C++实现离散余弦变换(参数为Eigen矩阵)
C++实现离散余弦变换(参数为Eigen矩阵) 问题描述 昨天写了一个参数为二维指针为参数的离散余弦变换,虽然改进了参数为二维数组时,当数组大小不确定时声明函数时带来的困难,但使用指针作为参数也存在一 ...
- Matlab/Eigen矩阵填充问题
Matlab进行矩阵填充时可以填充空矩阵,相当于空矩阵不存在,例如一下代码: P_RES = [ P_xv P_xvy P_xv*dy_dxv'; P_yxv P_y P_yxv*dy_dxv'; d ...
- Eigen 矩阵库学习笔记
最近为了在C++中使用矩阵运算,简单学习了一下Eigen矩阵库.Eigen比Armadillo相对底层一点,但是只需要添加头文库即可使用,不使用额外的编译和安装过程. 基本定义 Matrix3f是3* ...
- eigen矩阵操作练习
// // Created by qian on 19-7-16. // /* 相机位姿用四元数表示 q = [0.35, 0.2, 0.3, 0.1] x,y,z,w * 注意:输入时Quatern ...
- 矩阵基本运算的 Python 实现
from...import与import区别在于import直接导入指定的库,而from....import则是从指定的库中导入指定的模块 import...as则是将import A as B,给予 ...
- C++矩阵库 Eigen 快速入门
最近需要用 C++ 做一些数值计算,之前一直采用Matlab 混合编程的方式处理矩阵运算,非常麻烦,直到发现了 Eigen 库,简直相见恨晚,好用哭了. Eigen 是一个基于C++模板的线性代数库, ...
- C++矩阵库 Eigen 简介
最近需要用 C++ 做一些数值计算,之前一直采用Matlab 混合编程的方式处理矩阵运算,非常麻烦,直到发现了 Eigen 库,简直相见恨晚,好用哭了. Eigen 是一个基于C++模板的线性代数库, ...
- Eigen ,MKL和 matlab 矩阵乘法速度比较
Eigen 矩阵乘法的速度 < MKL矩阵乘法的速度,MKL矩阵乘法的速度与matlab矩阵乘法的速度相差不大,但matlab GPU版本的矩阵乘法速度是CUP的两倍,在采用float数据类型 ...
- OpenCV - Operations on Arrays 对数组(矩阵)的一些操作
Function (函数名) Use (函数用处) add 矩阵加法,A+B的更高级形式,支持mask scaleAdd 矩阵加法,一个带有缩放因子dst(I) = scale * src1(I) + ...
随机推荐
- MySQL 列,可选择的数据类型(通过sql命令查看:`help create table;`)
MySQL 列,可选择的数据类型(通过sql命令查看:help create table;) BIT[(length)] | TINYINT[(length)] [UNSIGNED] [ZEROFIL ...
- 从头调试stm32 HID
目录: 第1部分:参照“正点原子USB虚拟串口工程移植步骤”移植ST的USB HID工程(失败了): 第2部分:在1的基础上,替换USB HID初始化代码为ST 例程中的代码,编译后根据报错调试(失败 ...
- PCB行业研究
PCB行业研究 PCB产业上下游 关于HDI电路板 主要用于手机行业,对电路板面积有严格要求. 啥时候铜材料上涨
- Java种的String
String中的常用方法 subString()的使用,charAt的使用方法: indexof等的用法 String和byte的转换,对于程序过程的传输很重要, ==和equals的比较 1equa ...
- springMVC接收参数的区别form data与query string parameters与request payload
在AJAX请求中,我见过有三种form表单数据类型提交. 第一种:form data, 第二种:query string parameters,第三种:request payload. 在google ...
- C/C++中的volatile简单描述
首先引入一篇博客: 1. 为什么用volatile? C/C++ 中的 volatile 关键字和 const 对应,用来修饰变量,通常用于建立语言级别的 memory barrier.这是 BS 在 ...
- Runtime 解读
首先,第一个问题, 1>runtime实现的机制是什么,怎么用,一般用于干嘛? 这个问题我就不跟大家绕弯子了,直接告诉大家, runtime是一套比较底层的纯C语言API, 属于1个C语言库, ...
- 装饰器 -- 函数装饰器(tornado异常响应装饰器)
# 值可变,每次使用需要重新赋值 ERR_RESP_TEMPLATE = {"state": "FAILED", "error": None ...
- TCARS: Time- and Community-Aware Recommendation System(时间感知和社区感知推荐系统)
随着用户在物品上产生了大量行为,推荐系统成为了线上系统的重要组成部分.推荐系统算法使用用户对物品的行为信息以及上下文数据为每个用户推荐一组物品.算法根据用户之间及物品之间的相似度建立.本文介绍了一个基 ...
- logback的使用和logback.xml详解,在Spring项目中使用log打印日志
logback的使用和logback.xml详解 一.logback的介绍 Logback是由log4j创始人设计的另一个开源日志组件,官方网站: http://logback.qos.ch.它当前分 ...