Tuesday, 18 November 2014

New Matrix

class Matrix {
  int[][] mat;
  int error;
  Matrix(int[][] mat) {
    this.mat = mat;
    this.error = 0;
  }
  Matrix() {
    this.error = 1;
  }
  String toString() {
    if( this.error == 0){
    String print = "Matrix";
    for (int i = 0; i < this.mat.length; i++) {
      print = print+" Row"+i+"#";
      for (int j = 0; j < this.mat[i].length; j++) {
        print = print+" "+this.mat[i][j];
      }
    }
    return print;
  }
  else{
    String print = "ERROR";
    return print;
  }
  }
  Matrix add(Matrix in) {
      if (this.mat.length != in.mat.length) {
      Matrix sum = new Matrix();
      return sum;
    } else {
      int[][] result = new int[this.mat.length][this.mat[0].length];
      for (int i = 0; i < this.mat.length; i++) {
        for (int j = 0; j < this.mat[i].length; j++) {
          result [i][j] = this.mat[i][j]+in.mat[i][j];
        }
      }
      Matrix sum = new Matrix(result);
      return sum;
    }
  }
  Matrix minus(Matrix in) {
      if (this.mat.length != in.mat.length) {
      Matrix sum = new Matrix();
      return sum;
    } else {
      int[][] result = new int[this.mat.length][this.mat[0].length];
      for (int i = 0; i < this.mat.length; i++) {
        for (int j = 0; j < this.mat[i].length; j++) {
          result [i][j] = this.mat[i][j]-in.mat[i][j];
        }
      }
      Matrix sum = new Matrix(result);
      return sum;
    }
  }
}
int[][] math = {
  {
    5, 5, 5
  }
  , {
    4, 4, 4
  }
  , {
    2, 2, 2
  }
};
int[][] math2 = {
  {
    5, 5, 5
  }
  , {
    4, 4, 4
  }
  , {
    2, 2, 2
  }
};
Matrix m;
Matrix m2;
void setup() {
  m = new Matrix(math);
  m2 = new Matrix(math2);
  println(m.add(m2));
  println(m.minus(m2));
}

No comments:

Post a Comment