【问题标题】:How to build 3x3 translation matrix in c++如何在 C++ 中构建 3x3 平移矩阵
【发布时间】:2020-12-18 15:35:25
【问题描述】:

我是 C++ 新手。我希望创建一个如下所示的 3x3 矩阵:

我希望 theta 成为我可以在矩阵之外定义的参数,并在进行矩阵乘法时将其插入。我该怎么做?

如果是 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]]
 


【问题讨论】:

  • 呃...std::array<std::array<int,3>,3>?
  • 注意它看起来像一个旋转矩阵,而不是一个平移矩阵:)

标签: c++ matrix vector


【解决方案1】:

如果你想稍微快一点,你不一定需要定义一个专门的类:

#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
*/

-- 编辑--

由于大众需求,这里是 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";
      }
}

【讨论】:

  • 你也可以使用“Mat3x3 rotationMatrix(double theta)”。
【解决方案2】:

类似这样的:

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;
};

【讨论】:

    【解决方案3】:

    我认为这是一个更好的解决方案:

    
    #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;
    }
    
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-03-19
      • 1970-01-01
      • 2019-04-26
      相关资源
      最近更新 更多