Last active
May 30, 2022 15:11
-
-
Save kbridge/7a5cdf3fe3986e2abdd69a7b44bc0f8b to your computer and use it in GitHub Desktop.
A demo of using Eigen3 as a vector arithmetic library
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// https://eigen.tuxfamily.org/dox/GettingStarted.html | |
// https://eigen.tuxfamily.org/dox/group__TutorialMatrixArithmetic.html | |
// | |
// SeeAlso: https://www.boost.org/doc/libs/1_79_0/libs/qvm/doc/html/index.html | |
#define EIGEN_INITIALIZE_MATRICES_BY_ZERO | |
#include <iostream> | |
#include <Eigen/Dense> | |
int main() | |
{ | |
using namespace Eigen; | |
using namespace std; | |
// Vector3 is a 3x1 matrix | |
IOFormat vec( | |
StreamPrecision, // precision: use iostream settings | |
0, // flags | |
"", // coeffSeparator | |
",", // rowSeparator: | |
// no need to add spaces here | |
// because Eigen will use the 'fill' argument (defaults to ' ') | |
// to "fill the empty space in aligned columns" | |
"", // rowPrefix | |
"", // rowSuffix | |
"(", // matPrefix | |
")"); // matSuffix | |
Vector3d u(1, 2, 3); | |
Vector3d v(0, 2, 1); | |
cout << "---\n"; | |
cout << u << '\n'; | |
cout << "---\n"; | |
cout << u.format(vec) << '\n'; | |
cout << v.format(vec) << '\n'; | |
cout << "---\n"; | |
cout << " add: " << (u + v).format(vec) << '\n'; | |
cout << " subtract: " << (u - v).format(vec) << '\n'; | |
cout << "component-wise multiply: " << u.cwiseProduct(v).format(vec) << '\n'; | |
cout << " left scale: " << (7 * u).format(vec) << '\n'; | |
cout << " right scale: " << (u * 7).format(vec) << '\n'; | |
cout << " negate: " << (-u).format(vec) << '\n'; | |
cout << " dot product: " << u.dot(v) << '\n'; | |
cout << " cross product: " << u.cross(v).format(vec) << '\n'; | |
cout << " length: " << u.norm() << '\n'; // sqrt(14) | |
cout << " normalize: " << u.normalized().format(vec) << '\n'; | |
cout << " equals[1]: " << (u == u) << '\n'; | |
cout << " equals[2]: " << (u == v) << '\n'; | |
cout << "---\n"; | |
cout << "x: " << u.x() << '\n'; | |
cout << "y: " << u.y() << '\n'; | |
cout << "z: " << u.z() << '\n'; | |
cout << "---\n"; | |
cout << "zero: " << Vector3d().format(vec) << '\n'; // EIGEN_INITIALIZE_MATRICES_BY_ZERO | |
cout << "---\n"; | |
cout << "swizzle:\n"; | |
cout << " xy: " << u({0, 1}).format(vec) << '\n'; | |
cout << " yz: " << u({1, 2}).format(vec) << '\n'; | |
cout << " zx: " << u({2, 0}).format(vec) << '\n'; | |
cout << " yy: " << u({1, 1}).format(vec) << '\n'; | |
cout << "zyx: " << u({2, 1, 0}).format(vec) << '\n'; | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment