This is a simple template matrix class with enbrace-enclosed constructor. Save it as tMatrix.h, and place it in your working directory together with the .cpp file.
#ifndef __matrix_class___
#define __matrix_class___
#include <iostream>
#include <initializer_list>
#include <iomanip>
#include <complex>
template <typename T> class tMatrix
{
public:
T *ptr;
int col, row, size;
inline T* begin() const {return ptr;}
inline T* end() const {return this->ptr + this->size;}
inline T operator()(const int i, const int j)const { return ptr[i*col+j]; }
inline T&operator()(const int i, const int j) { return ptr[i*col+j]; }
inline tMatrix(): col{0}, row{0}, size{0}, ptr{0} {;}
tMatrix(const int i, const int j): col(j), row(i), size(i*j)
{
ptr = new T [this->size] ;
}
tMatrix(const std::initializer_list< std::initializer_list<T> > s):tMatrix<T>(s.size(), s.begin()->size())
{
int j = 0;
for (const auto& i : s) { std::copy (i.begin(), i.end(), ptr + j*col); ++j ; }
}
tMatrix(const tMatrix<T>&a) : tMatrix<T>(a.row, a.col)
{
std::copy(a.begin(), a.end(), this->ptr);
}
tMatrix& operator=(const tMatrix<T>&a)
{
std::copy(a.begin(), a.end(), this->ptr);
return *this;
}
~tMatrix() {delete [] this->ptr;}
};
template <typename X> std::ostream& operator<<(std::ostream&p, const tMatrix<X>&a)
{
p << std::fixed;
for (int i=0; i<a.row; i++) {
for (int j=0; j <a.col; j++) p << std::setw(12) << a(i, j);
p << std::endl;
}
return p;
}
using iMatrix = tMatrix<int>;
using rMatrix = tMatrix<double>;
using cMatrix = tMatrix<std::complex<double> >;
#endif
Then modify your program as:
#include <cmath>
#include "tMatrix.h"
using namespace std;
rMatrix makeMatrix (const char c, double a) {
rMatrix mtx(3,3);
double cs = cos(a), ss = sin(a);
switch (c) {
case 'x' :
mtx = rMatrix( { {1, 0, 0}, {0, cs, -ss}, {0, ss, cs} } );
break;
case 'y' :
mtx = rMatrix( { {cs, 0, ss}, {0, 1, 0}, {-ss, 0, cs} } );
break;
case 'z' :
mtx = rMatrix( { {cs, -ss, 0}, {ss, cs, 0}, {0, 0, 1} } );
break;
default:
break;
}
return mtx;
}
int main()
{
char axis = 'x';
double angle = M_PI / 180. * 60.;
rMatrix mtx = {{0,0,0}, {0,0,0}, {0,0,0}}; //initial a 3x3 matrix with all 0s
std::cout << mtx << std::endl;
std::cout << makeMatrix(axis, angle) <<std::endl;
return 0;
}