2 views
in Java
I was trying to write a program on matrix multiplication which should return an identity matrix. But, it is not working. I am using a multi-dimensional array. Can anyone help me with this?

by (26.7k points)

You can try with the below code, which will help you get an identity matrix:

public class Intellipaat {

Double[][] A = { { 4.00, 3.00 }, { 2.00, 1.00 } };

Double[][] B = { { -0.500, 1.500 }, { 1.000, -2.0000 } };

public static Double[][] multiple(Double[][] A, Double[][] B) {

int aRows = A.length;

int aColumns = A[0].length;

int bRows = B.length;

int bColumns = B[0].length;

if (aColumns != bRows) {

throw new IllegalArgumentException("A:Rows: " + aColumns + " did not match B:Columns " + bRows + ".");

}

Double[][] C = new Double[aRows][bColumns];

for (int i = 0; i < aRows; i++) {

for (int j = 0; j < bColumns; j++) {

C[i][j] = 0.00000;

}

}

for (int i = 0; i < aRows; i++) { // aRow

for (int j = 0; j < bColumns; j++) { // bColumn

for (int k = 0; k < aColumns; k++) { // aColumn

C[i][j] += A[i][k] * B[k][j];

}

}

}

return C;

}

public static void main(String[] args) {

Intellipaat matrix = new Intellipaat();

Double[][] result = multiple(matrix.A, matrix.B);

for (int i = 0; i < 2; i++) {

for (int j = 0; j < 2; j++)

System.out.print(result[i][j] + " ");

System.out.println();

}

}

}

I hope this will help.

Want to become a Java Expert? Join Java Certification now!!

Want to know more about Java? Watch this video on Java Training | Java Course for Beginners:

+1 vote