用c语言写一个三维坐标系的旋转矩阵
时间: 2023-10-15 15:06:01 浏览: 249
以下是用C语言写的三维旋转矩阵代码,可以根据需要修改旋转角度和坐标轴:
```c
#include <stdio.h>
#include <math.h>
#define PI 3.14159265
// 三维向量结构体
typedef struct {
double x, y, z;
} Vector3;
// 旋转矩阵结构体
typedef struct {
double m[3][3];
} Matrix3x3;
// 初始化旋转矩阵
Matrix3x3 init_rotation_matrix(double angle, char axis) {
Matrix3x3 matrix;
double radian = angle * PI / 180.0;
double c = cos(radian);
double s = sin(radian);
switch (axis) {
case 'x':
matrix.m[0][0] = 1.0;
matrix.m[1][1] = c;
matrix.m[1][2] = -s;
matrix.m[2][1] = s;
matrix.m[2][2] = c;
break;
case 'y':
matrix.m[0][0] = c;
matrix.m[0][2] = s;
matrix.m[1][1] = 1.0;
matrix.m[2][0] = -s;
matrix.m[2][2] = c;
break;
case 'z':
matrix.m[0][0] = c;
matrix.m[0][1] = -s;
matrix.m[1][0] = s;
matrix.m[1][1] = c;
matrix.m[2][2] = 1.0;
break;
default:
break;
}
return matrix;
}
// 矩阵乘法
Matrix3x3 matrix_multiply(Matrix3x3 a, Matrix3x3 b) {
Matrix3x3 c;
int i, j, k;
for (i = 0; i < 3; i++) {
for (j = 0; j < 3; j++) {
c.m[i][j] = 0.0;
for (k = 0; k < 3; k++) {
c.m[i][j] += a.m[i][k] * b.m[k][j];
}
}
}
return c;
}
// 旋转向量
Vector3 rotate_vector(Vector3 vector, Matrix3x3 matrix) {
Vector3 result;
result.x = matrix.m[0][0] * vector.x + matrix.m[0][1] * vector.y + matrix.m[0][2] * vector.z;
result.y = matrix.m[1][0] * vector.x + matrix.m[1][1] * vector.y + matrix.m[1][2] * vector.z;
result.z = matrix.m[2][0] * vector.x + matrix.m[2][1] * vector.y + matrix.m[2][2] * vector.z;
return result;
}
int main() {
// 测试代码
Vector3 vector = {1.0, 0.0, 0.0};
Matrix3x3 matrix = init_rotation_matrix(45.0, 'z');
Vector3 result = rotate_vector(vector, matrix);
printf("result: (%f, %f, %f)\n", result.x, result.y, result.z);
return 0;
}
```
该代码中定义了一个三维向量结构体和一个三维旋转矩阵结构体。`init_rotation_matrix`函数用于初始化旋转矩阵,根据旋转角度和坐标轴生成一个旋转矩阵;`matrix_multiply`函数用于矩阵乘法;`rotate_vector`函数用于旋转三维向量。在`main`函数中,我们测试了一个向量绕z轴旋转45度后的结果。
阅读全文