Categories
Interview java matrix

multiply two matrix using java with example

In this post, we will learn about multiply two matrix in java with example

We are declaring two matrix named as a,b and one more variable mul to store the multiplication of a&b matrix

Example
public class MatrixMultiplication {

	public static void main(String[] args) {
		try {

			int a[][] = { { 50, 60 }, { 20, 15 } };
			int b[][] = { { 25, 20 }, { 10, 5 } };

			// Declaring the diff matrix
			int[][] mul = new int[a.length][b.length];

			// multiply 2 matrices
			for (int i = 0; i < a.length; i++) {
				for (int j = 0; j < b.length; j++) {
					mul[i][j] = 0;
					for (int k = 0; k < 2; k++) {
						mul[i][j] += a[i][k] * b[k][j];
					}
					System.out.print(mul[i][j] + " ");
				}
				System.out.println();
			}

		} catch (Exception e) {
			e.printStackTrace();
		}
	}

}
Output
1850  1300 
650   475 
Github

https://github.com/rkumar9090/BeginnersBug/blob/master/BegineersBug/src/com/geeks/example/MatrixMultiplication.java

Related Articles

subtracting two matrix in java with example