Lesson 14 Usage as temporary objects

来源:互联网 发布:弹幕源码 编辑:程序博客网 时间:2024/06/04 21:13

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()
{
MatrixXd m =MatrixXd::Random(3,3);
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.549.4  101 86.888.3 29.8 37.8m * v =404512261

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:
MatrixXf mat =MatrixXf::Random(2, 3);
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.

0 0
原创粉丝点击