I am new to c++. I am looking to create a 3x3 matrix that looks like this:
I want theta to be a parameter that I can define outside of the matrix and plug it in when doing matrix multiplication. How do I do this?
If it were python, I'd want something like this:
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:
#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. Compiled with "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;
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.