C++_Eigen函数库用法笔记——The Array class and Coefficient-wise operations

  • The advantages of Array
  • Addition and subtraction
  • Array multiplication
  • abs() & sqrt()
  • Converting between array and matrix expressions
 

 
  • The advantage of Array
    • provides an easy way to perform coefficient-wise operations, such as adding a constant to every coefficient in the array or multiplying two arrays coefficient-wise
 
  • Addition and subtraction
int main()
{
ArrayXXf a(3,3);
a << 1,2,3,
  4,5,6,
  7,8,9;
cout << “a - 2 = “ <<endl << a - 2 << endl;
}
 
a - 2 = 
-1  0  1
 2  3  4
 5  6  7
 
  • Array multiplication
    • array multiply array, arrays interpret multiplication as coefficient-wise product.
    • two arrays can be multiplied if and only if they have the same dimensions.
int main()
{
ArrayXXf a(2,2);
ArrayXXf b(2,2);
a << 1,2,
3,4;
b << 5,6,
7,8;
cout << "a * b = " << endl << a * b << endl;
 
a * b = 
 5 12
21 32
  • abs() & sqrt()
    • the .abs() method takes the absolute value of each coefficient
    • the .sqrt() computes the square root of the coefficients
int main()
{
ArrayXf a = ArrayXf::Random(5);
a *= 2;
cout << "a =" << endl
<< a << endl;
cout << "a.abs() =" << endl
<< a.abs() << endl;
cout << "a.abs().sqrt() =" << endl
<< a.abs().sqrt() << endl;
cout << "a.min(a.abs().sqrt()) =" << endl
<< a.min(a.abs().sqrt()) << endl;
a =
  1.36
-0.422
  1.13
  1.19
  1.65
a.abs() =
 1.36
0.422
 1.13
 1.19
 1.65
a.abs().sqrt() =
1.17
0.65
1.06
1.09
1.28
 
  • Converting between array and matrix expressions
    • Mixing matrices and arrays in an expression is forbidden
int main()
{
MatrixXf m(2,2);
MatrixXf n(2,2);
MatrixXf result(2,2);
m << 1,2,
3,4;
n << 5,6,
7,8;
result = m * n;
cout << "-- Matrix m*n: --" << endl << result << endl << endl;
result = m.array() * n.array();
cout << "-- Array m*n: --" << endl << result << endl << endl;
result = m.cwiseProduct(n);
-- Matrix m*n: --
19 22
43 50

-- Array m*n: --
 5 12
21 32
 
 
Here is a more advanced example
int main()
{
MatrixXf m(2,2);
MatrixXf n(2,2);
MatrixXf result(2,2);
m << 1,2,
3,4;
n << 5,6,
7,8;
result = (m.array() + 4).matrix() * m;
cout << "-- Combination 1: --" << endl << result << endl << endl;
result = (m.array() * n.array()).matrix() * m;
cout << "-- Combination 2: --" << endl << result << endl << endl;
-- Combination 1: --
23 34
31 46

-- Combination 2: --
 41  58
117 170
 
 
 
 
posted @ 2016-03-09 20:43  一鸣先森  阅读(940)  评论(0编辑  收藏  举报