什么是Array类?
与Matrix与线性代数相关,Array类提供一个通用的数组。具体的,Array能够提供一个coefficient-wise操作,该类操作是没有线性代数意义的。如,增加一个常数到array每一个元素(coefficient)中,或者两个array对应元素相乘。
coefficient-wise个人理解应该是逐元素运算,换句话说就是每个元素都执行的运算。
Array类
Array类也是一个模板参数,他和Matrix的模板参数完全一样。
Array<typename Scalar, int RowsAtCompileTime, int ColsAtCompileTime>
同样也提供一些typedef方便用户使用:
类型 | 别名 |
---|---|
Array<float,Dynamic,1> | ArrayXf |
Array<float,3,1> | Array3f |
Array<double,Dynamic,Dynamic> | ArrayXXd |
Array<double,3,3> | Array33d |
获取Array中的值
和Matrix操作一样,不再赘述。
#include <Eigen/Dense>
#include <iostream>
using namespace Eigen;
using namespace std;
int main()
{
ArrayXXf m(2,2);
// assign some values coefficient by coefficient
m(0,0) = 1.0; m(0,1) = 2.0;
m(1,0) = 3.0; m(1,1) = m(0,1) + m(1,0);
// print values to standard output
cout << m << endl << endl;
// using the comma-initializer is also allowed
m << 1.0,2.0,
3.0,4.0;
// print values to standard output
cout << m << endl;
}
加法和减法
#include <Eigen/Dense>
#include <iostream>
using namespace Eigen;
using namespace std;
int main()
{
ArrayXXf a(3,3);
ArrayXXf b(3,3);
a << 1,2,3,
4,5,6,
7,8,9;
b << 1,2,3,
1,2,3,
1,2,3;
// Adding two arrays
cout << "a + b = " << endl << a + b << endl << endl;
// Subtracting a scalar from an array
cout << "a - 2 = " << endl << a - 2 << endl;
}
在Matrix类中,我们无法实现scalar与Matrix的加法运算是未定义的,但是array确定义了行为:每个元素都进行一个scalar加减计算。
乘法
首先,和Matrix一样,scalararray表现的是数乘;其次,与Matrix不同,arrayarray表现的是coeffecient-wise乘法,即对应元素相乘,而不是矩阵乘法。
#include <Eigen/Dense>
#include <iostream>
using namespace Eigen;
using namespace std;
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;
}
其他coefficient-wise运算
#include <Eigen/Dense>
#include <iostream>
using namespace Eigen;
using namespace std;
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;
}
array与matrix的互换
什么时候应该用array?什么时候又应该用matrix?
- 当你需要coefficient-wise运算时使用array
- 当你只需要用到线性代数运算时用matrix
有时候两种都需要用到怎么办?通过转换!
- matrix有array方法
- array有matrix方法