c++实现欧拉角计算旋转矩阵
时间: 2024-12-31 14:30:38 浏览: 63
### 实现欧拉角到旋转矩阵转换
为了实现从欧拉角到旋转矩阵的转换,在 C++ 中可以按照如下方式构建函数:
```cpp
#include <cmath>
struct Vector3 {
double x, y, z;
};
// 定义一个 3x3 的旋转矩阵结构体
struct Matrix3x3 {
double m[3][3];
void setIdentity() {
for (int i = 0; i < 3; ++i) {
for (int j = 0; j < 3; ++j) {
m[i][j] = (i == j);
}
}
}
static Matrix3x3 fromEulerAngles(const Vector3& eulerAngles) {
const double roll = eulerAngles.x * M_PI / 180.0;
const double pitch = eulerAngles.y * M_PI / 180.0;
const double yaw = eulerAngles.z * M_PI / 180.0;
// 计算各个轴上的旋转变换矩阵
// 绕 X 轴旋转矩阵 R_x(roll)
Matrix3x3 Rx;
Rx.setIdentity();
Rx.m[1][1] = cos(roll); Rx.m[1][2] = -sin(roll);
Rx.m[2][1] = sin(roll); Rx.m[2][2] = cos(roll);
// 绕 Y 轴旋转矩阵 R_y(pitch)
Matrix3x3 Ry;
Ry.setIdentity();
Ry.m[0][0] = cos(pitch); Ry.m[0][2] = sin(pitch);
Ry.m[2][0] = -sin(pitch); Ry.m[2][2] = cos(pitch);
// 绕 Z 轴旋转矩阵 R_z(yaw)
Matrix3x3 Rz;
Rz.setIdentity();
Rz.m[0][0] = cos(yaw); Rz.m[0][1] = -sin(yaw);
Rz.m[1][0] = sin(yaw); Rz.m[1][1] = cos(yaw);
// 将三个基本旋转组合成最终变换矩阵
return multiply(multiply(Rz, Ry), Rx);
}
private:
static Matrix3x3 multiply(const Matrix3x3 &A, const Matrix3x3 &B) {
Matrix3x3 result;
for(int row=0;row<3;++row){
for(int col=0;col<3;++col){
result.m[row][col]= A.m[row][0]*B.m[0][col]+A.m[row][1]*B.m[1][col]+A.m[row][2]*B.m[2][col];
}
}
return result;
}
};
```
上述代码定义了一个 `Matrix3x3` 结构用于表示三维空间中的旋转矩阵,并实现了通过给定的欧拉角度创建对应的旋转矩阵的功能。这里假设输入的角度是以度数形式给出并将其转换为弧度来执行三角运算[^2]。
阅读全文
相关推荐

















