C++開源矩陣計算工具——Eigen的簡單用法(二)
阿新 • • 發佈:2019-02-19
本文主要是Eigen中矩陣和向量的算術運算,在Eigen中的這些算術運算過載了C++的+,-,*,所以使用起來非常方便。
1、矩陣的運算
Eigen提供+、-、一元操作符“-”、+=、-=,例如:
二元操作符+/-表示兩矩陣相加(矩陣中對應元素相加/減,返回一個臨時矩陣): B+C 或 B-C;
一元操作符-表示對矩陣取負(矩陣中對應元素取負,返回一個臨時矩陣): -C;
組合操作法+=或者-=表示(對應每隔元素都做相應操作):A += B 或者 A-=B
程式碼段1為矩陣的加減操作,程式碼如下:
輸出結果為:#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
另外,矩陣還提供與標量(單一個數字)的乘除操作,表示每個元素都與該標量進行乘除操作。例如:
二元操作符*在:A*a中表示矩陣A中的每隔元素都與數字a相乘,結果放在一個臨時矩陣中,矩陣的值不會改變。
對於a*A、A/a、A*=a、A /=a也是一樣,例如下面的程式碼:
輸出結果為:#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
需要注意:
在Eigen中,算術操作例如 “操作符+”並不會自己執行計算操作,他們只是返回一個“算術表示式物件”,而實際的計算則會延遲到後面的賦值時才進行。這些不影響你的使用,它只是為了方便Eigen的優化。
2、求矩陣的轉置、共軛矩陣、伴隨矩陣。
例如下面的程式碼所示:
輸出結果為:MatrixXcf a = MatrixXcf::Random(2,2); cout << "Here is the matrix a\n" << a << endl; cout << "Here is the matrix a^T\n" << a.transpose() << endl; cout << "Here is the conjugate of a\n" << a.conjugate() << endl; cout << "Here is the matrix a^*\n" << a.adjoint() << endl;
Here is the matrix a (-0.211,0.68) (-0.605,0.823) (0.597,0.566) (0.536,-0.33) Here is the matrix a^T (-0.211,0.68) (0.597,0.566) (-0.605,0.823) (0.536,-0.33) Here is the conjugate of a (-0.211,-0.68) (-0.605,-0.823) (0.597,-0.566) (0.536,0.33) Here is the matrix a^* (-0.211,-0.68) (0.597,-0.566) (-0.605,-0.823) (0.536,0.33)3、矩陣相乘、矩陣向量相乘
矩陣的相乘,矩陣與向量的相乘也是使用操作符*,共有*和*=兩種操作符,其用法可以參考如下程式碼:
#include <iostream>
#include <Eigen/Dense>
using namespace Eigen;
int main()
{
Matrix2d mat;
mat << 1, 2,
3, 4;
Vector2d u(-1,1), v(2,0);
std::cout << "Here is mat*mat:\n" << mat*mat << std::endl;
std::cout << "Here is mat*u:\n" << mat*u << std::endl;
std::cout << "Here is u^T*mat:\n" << u.transpose()*mat << std::endl;
std::cout << "Here is u^T*v:\n" << u.transpose()*v << std::endl;
std::cout << "Here is u*v^T:\n" << u*v.transpose() << std::endl;
std::cout << "Let's multiply mat by itself" << std::endl;
mat = mat*mat;
std::cout << "Now mat is mat:\n" << mat << std::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 itself Now mat is mat: 7 10 15 22