Skip to main content
6 of 6
deleted 58 characters in body
Jamal
  • 34.9k
  • 13
  • 133
  • 237

Numerical algebra using a Matrix class

I would like to make a Matrix class. Can any of you help me about this class?

There are two ways:

#include <iostream>

class Matrix {
    
private:
    double** array;
    int row, column;
    
public:

    Matrix(int m, int n) {
        this->row=m;
        this->column=n;
        this->array = new double*[m];
        for (int i = 0; i < n; i++){
            this->array[i] = new double[n];
            std::fill(array[i],array[i]+n,0.0);
        }
    }

    Matrix(Matrix &matrix){
        this->array=matrix.array;
        this->row=matrix.row;
        this->column=matrix.column;
        
    }
    Matrix& operator=(const Matrix& rhs ){
        this->row=rhs.row;
        this->column=rhs.column;
        for(int i=0;i<row;++i)
            for(int j=0;j<column;++j)
                this->array[i][j]=rhs.array[i][j];
    }

    ~Matrix() {
        for (int i = 0; i < this->row; i++)
            delete[] this->array[i];
        delete[] this->array;
    }

   void print(){
        for(int i=0;i<this->row;++i){
            for(int j=0;j<this->column;++j)
                printf("%f\t",this->array[i][j]);
            printf("\n");
        }
        
    }
    double * operator [](int m){
        return this->array[m];
    }
};
int main(int argc, const char * argv[]) {
    Matrix A(2,2);
    A[0][1]=1;
    A[0][0]=0;
    A[1][0]=1;
    A[1][1]=1;
    A.print();
    return 0;
  }

The other one using vector:

#include <iostream>
#include <vector>

using namespace std;

class Matrix {

private:
vector< vector<double> > array;
int row, column;

public:

Matrix(int m, int n) {
    row = m;
    column = n;
    array = vector< vector<double> > (m, vector<double> (n, 0));
}


Matrix(Matrix &matrix){
    this->array=matrix.array;
    this->row=matrix.row;
    this->column=matrix.column;
    
}
void print(){
    for(int i=0;i<this->row;++i){
        for(int j=0;j<this->column;++j)
            printf("%f\t",this->array[i][j]);
        printf("\n");
    }
    
 }
 vector<double> & operator [](int m){
     return this->array[m];
 }
 };