[英]How to build 3x3 translation matrix in c++
I am new to c++.我是 c++ 的新手。 I am looking to create a 3x3 matrix that looks like this:我希望创建一个如下所示的 3x3 矩阵:
I want theta to be a parameter that I can define outside of the matrix and plug it in when doing matrix multiplication.我希望 theta 成为我可以在矩阵之外定义的参数,并在进行矩阵乘法时将其插入。 How do I do this?我该怎么做呢?
If it were python, I'd want something like this:如果是 python,我想要这样的东西:
define matrix(theta):
row1 = np.array([cos(theta), -sin(theta), 0])
row2 = np.array([sin(theta), cos(theta), 0])
row3 = np.array([0,0,1])
matrix = np.stack([row1, row2, row3])
return matrix
In[] matrix(2)
Out[]
[[cos(2), -sin(2), 0],
[sin(2), cos(2), 0],
[0, 0, 1]]
Something like this:像这样的东西:
class RotationMatrix
{
public:
RotationMatrix(const double radians)
: m({{cos(radians, -sin(radians), 0}, {sin(radians), cos(radians), 0}, {0, 0, 1}}) {}
private:
std::array<std::array<double, 3>, 3> m;
};
You don't necessarily need to define a dedicated class if you want to go a bit quick and dirty:如果你想 go 有点快和脏,你不一定需要定义一个专用的 class :
#include <iostream>
#include <cmath>
#include <array>
using Mat3x3 = std::array<std::array<double, 3>, 3>;
auto rotationMatrix(double theta)
{
Mat3x3 mat
{ std::array{ cos(theta), -sin(theta), 0. },
std::array{ sin(theta), cos(theta), 0. },
std::array{ 0., 0., 1. } };
return mat;
}
int main()
{
auto mat = rotationMatrix(0.1);
for (const auto& row : mat)
{
for (const auto& col : row)
std::cout << col << " ";
std::cout << "\n";
}
}
/* prints:
0.995004 -0.0998334 0
0.0998334 0.995004 0
0 0 1
*/
-- EDIT -- - 编辑 -
Here is C++11 version due to popular demand.由于大众需求,这里是 C++11 版本。 Compiled with "g++ mat3.cc --std=c++11"用“g++ mat3.cc --std=c++11”编译
#include <iostream>
#include <cmath>
#include <array>
using Mat3x3 = std::array<std::array<double, 3>, 3>;
Mat3x3 translationMatrix(double theta)
{
Mat3x3 mat
{ std::array<double, 3> { cos(theta), -sin(theta), 0. },
std::array<double, 3> { sin(theta), cos(theta), 0. },
std::array<double, 3> { 0., 0., 1. } };
return mat;
}
int main()
{
Mat3x3 mat = translationMatrix(0.1);
for (const auto& row : mat)
{
for (const auto& col : row)
std::cout << col << " ";
std::cout << "\n";
}
}
I think this would a better solution:我认为这将是一个更好的解决方案:
#include <array>
#include <math.h>
#include <iostream>
typedef std::array<std::array<int,3>,3> Matrix3X3;
Matrix3X3 getMatrix(int x) {
Matrix3X3 matrix;
matrix[0][0] = //sin of x;
//...and so on
return matrix;
}
int main() {
Matrix3X3 matrix = getMatrix(3);
return 0;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.