Lesson 14 Usage as temporary objects

本文介绍如何在Eigen库中使用静态方法初始化矩阵变量,包括使用常数矩阵和表达式对象来创建临时矩阵,同时展示如何在赋值操作中进行矩阵运算。

As shown above, static methods as Zero() and Constant() can be used to initialize variables at the time of declaration or at the right-hand side of an assignment operator. You can think of these methods as returning a matrix or array; in fact, they return so-called expression objects which evaluate to a matrix or array when needed, so that this syntax does not incur any overhead.

These expressions can also be used as a temporary object. The second example in the Getting started guide, which we reproduce here, already illustrates this.

Example: Output:
#include <iostream>
#include <Eigen/Dense>
using namespace Eigen;
using namespace std;
int main()
{
m = (m + MatrixXd::Constant(3,3,1.2)) * 50;
cout << "m =" << endl << m << endl;
VectorXd v(3);
v << 1, 2, 3;
cout << "m * v =" << endl << m * v << endl;
}
m =
  94 89.8 43.5
49.4  101 86.8
88.3 29.8 37.8
m * v =
404
512
261

The expression m + MatrixXf::Constant(3,3,1.2) constructs the 3-by-3 matrix expression with all its coefficients equal to 1.2 plus the corresponding coefficient of m.

The comma-initializer, too, can also be used to construct temporary objects. The following example constructs a random matrix of size 2-by-3, and then multiplies this matrix on the left with $ \bigl[ \begin{smallmatrix} 0 & 1 \\ 1 & 0 \end{smallmatrix} \bigr] $.

Example: Output:
std::cout << mat << std::endl << std::endl;
mat = ( MatrixXf(2,2) << 0, 1, 1, 0).finished() * mat;
std::cout << mat << std::endl;
  0.68  0.566  0.823
-0.211  0.597 -0.605

-0.211  0.597 -0.605
  0.68  0.566  0.823

The finished() method is necessary here to get the actual matrix object once the comma initialization of our temporary submatrix is done.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值