AkashiRobo / Mbed OS matrix_lib

matrix.h

Committer:
minamikawa
Date:
2021-04-13
Revision:
0:1adddb4d1d6a

File content as of revision 0:1adddb4d1d6a:

#ifndef MATRIX2_LIB
#define MATRIX2_LIB

#include<vector>

using namespace std;

template <class T>
class Matrix{
    private:
        vector<vector<T>> matrix;
        int row;
        int col;
    public:
        Matrix(int n, int m, T initNum):row(n), col(m), matrix(vector<vector<T>>(n, vector<T>(m))){
            for(int i=0;i<row;i++){
                for(int j=0;j<col;j++){
                    matrix[i][j] = initNum;
                }
            }
        }
        Matrix(int n, int m):row(n), col(m), matrix(vector<vector<T>>(n, vector<T>(m))){}
        
        ~Matrix(){}
        
        void show(){
            for(int i=0;i<row;i++){
                for(int j=0;j<col;j++){
                }
            }
        }

        vector<T> operator[](const int i) const{return matrix[i];}
        vector<T>& operator[](const int i){return matrix[i];}

        Matrix& operator=(const Matrix& a){
            if((row == a.row) && (col == a.col)){
                row = a.row;
                col = a.col;
                for(int i=0;i<row;i++){
                    for(int j=0;j<col;j++){
                        matrix[i][j] = a[i][j];
                    }
                }
            }else{

            }
            return *this;
        }

        Matrix& operator+=(const Matrix& a){
            for(int i=0;i<row;i++){
                for(int j=0;j<col;j++){
                    matrix[i][j] += a[i][j];
                }
            }
            return *this;
        }

        Matrix operator+(const Matrix& a) const {
            return Matrix(*this) += a;
        }

        Matrix& operator-=(const Matrix& a){
            for(int i=0;i<row;i++){
                for(int j=0;j<col;j++){
                    matrix[i][j] -= a[i][j];
                }
            }
            return *this;
        }
        
        Matrix operator-(const Matrix& a) const {
            return Matrix(*this) -= a;
        }

        Matrix& operator*=(const Matrix& a){
            Matrix<T> tmp(row, a.col);
            for(int i=0;i<row;i++){
                for(int j=0;j<a.col;j++){
                    for(int k=0;k<col;k++){
                        tmp[i][j] += matrix[i][k] * a[k][j];
                    }
                }
            }
            col = a.col;
            for(int i=0;i<row;i++){
                matrix[i].resize(col);
            }
            for(int i=0;i<row;i++){
                for(int j=0;j<col;j++){
                    matrix[i][j] = tmp[i][j];
                }
            }

            return *this;
        }
        
        Matrix operator*(const Matrix& a) const {
            return Matrix(*this) *= a;
        }
};


#endif