
all constructor for matrix class?

The given code implements the Matrix class and show the addition of two matrices.
public class Matrix{
int M;
int N;
int[][] data;
public Matrix(int M, int N) {
this.M = M;
this.N = N;
data = new int[M][N];
}
public Matrix(int[][] data) {
M = data.length;
N = data[0].length;
this.data = new int[M][N];
for (int i = 0; i < M; i++)
for (int j = 0; j < N; j++)
this.data[i][j] = data[i][j];
}
Matrix(Matrix A) {
this(A.data);
}
public Matrix plus(Matrix B) {
Matrix A = this;
if (B.M != A.M || B.N != A.N) throw new RuntimeException("Illegal matrix dimensions.");
Matrix C = new Matrix(M, N);
for (int i = 0; i < M; i++)
for (int j = 0; j < N; j++)
C.data[i][j] = A.data[i][j] + B.data[i][j];
return C;
}
public void show() {
for (int i = 0; i < M; i++) {
for (int j = 0; j < N; j++) {
System.out.print(data[i][j]+" ");
}
System.out.println();
}
}
public static void main(String[] args) {
int[][] arr1 = { { 1, 2, 3 }, { 4, 5, 6 }, { 9, 1, 3} };
Matrix A = new Matrix(arr1);
System.out.println("Matrix A: ");
A.show();
System.out.println();
int[][] arr2 = { { 2, 3, 4 }, { 1, 2, 3 }, { 4, 1, 2} };
Matrix B = new Matrix(arr2);
System.out.println("Matrix B: ");
B.show();
System.out.println();
System.out.println("Sum of two matrices: ");
A.plus(B).show();
System.out.println();
}
}
If you are facing any programming issue, such as compilation errors or not able to find the code you are looking for.
Ask your questions, our development team will try to give answers to your questions.