matrix class in c 2b 2b

Solutions on MaxInterview for matrix class in c 2b 2b by the best coders in the world

showing results for - "matrix class in c 2b 2b"
Sophia
10 Feb 2016
1
2template<class T>
3class matrix{
4    size_t ROW,COL;
5    vector<vector<T>> mat;
6public:
7    matrix(size_t N, size_t M, int populate = 0){
8        this->ROW = N;
9        this->COL = M;
10        this->mat = vector<vector<T>> (ROW,vector<T> (COL,populate));
11    }
12    matrix(size_t N, int populate = 0){
13        this->ROW = N;
14        this->COL = N;
15        this->mat = vector<vector<T>> (ROW,vector<T> (COL,populate));
16    }
17    void __init(){
18        for(int i = 0; i < ROW; ++i){
19            for(int j = 0; j < COL; ++j){
20                cin  >> this->mat[i][j];
21            }
22        }
23    }
24    void __display(){
25        for(int i = 0; i < ROW; ++i){
26            for(int j = 0; j < COL; ++j){
27                cout << this->mat[i][j] << " ";
28            }
29            cout << "\n";
30        }
31    }
32    matrix<T> operator*(const matrix &rhs)const{
33        if(this->COL != rhs.ROW){
34            throw "MATRIX MULTIPLICATION CANNOT HAPPEN WITH THE GIVEN MATRICES"
35        }
36        matrix<T> result(this->ROW,rhs.COL);
37        for(int _i = 0; _i < this->ROW; _i++){
38            for(int _j = 0; _j < rhs.COL; _j++){
39                result[_i][_j] = 0;
40                for(int _k = 0; _k < this->COL; ++_k){
41                    result[_i][_j]+=(this->mat[_i][_k]*rhs.mat[_k][_j]);
42                }
43            }
44        }
45        return result;
46    }
47    matrix<T> power(int n){
48        if(n == 0)return matrix<T>(this->ROW, this->COL,1);
49        if(n == 1)return *this;
50        matrix p = power(n/2);
51        p = p*p;
52        if(n%2)p = p*(*this);
53        return p;
54    }
55};