How do you write an algorithm for the multiplication of two matrix [2D array]?
Problem statement:
Given two matrices, the task is to multiply them. Matrices can either be square or rectangular.
Example:
Input: int m1[][] = {{2, 3, 4}, {5, 6, 7}}; // 2 X 3 matrix
int m2[][] = {{1, 2}, {3, 4}, {5, 6}}; // 3 X 2 matrix
Output: {{31, 40},{58,76}}
Given two matrices, the task is to multiply them. Matrices can either be square or rectangular.
Example:
Input: int m1[][] = {{2, 3, 4}, {5, 6, 7}}; // 2 X 3 matrix
int m2[][] = {{1, 2}, {3, 4}, {5, 6}}; // 3 X 2 matrix
Output: {{31, 40},{58,76}}
- public class MatrixMultiplication {
- public static void main(String args[]) {
- int m1[][] = {{2, 3, 4}, {5, 6, 7}}; // 2 X 3 matrix
- int m2[][] = {{1, 2}, {3, 4}, {5, 6}}; // 3 X 2 matrix
- int res[][] = new int[2][2]; // resultant matrix of 2 X 2
- for (int i = 0; i < 2; i++) { // i represent row
- for (int j = 0; j < 2; j++) { // j represent column
- res[i][j] = 0; // assume res[0][0] = 0
- for (int k = 0; k < 3; k++) {
- // k represent first matrix i.e. m1 -> number of column for // counter sum
- res[i][j] = res[i][j] + m1[i][k] * m2[k][j];
- }
- }
- }
- // printing the resultant matrix
- for (int i = 0; i < 2; i++) {
- for (int j = 0; j < 2; j++) {
- System.out.print(res[i][j] + " ");
- }
- System.out.println();
- }
- }
- }
Method-II:
- public class MatrixMultiplication2D {
- public static void main(String args[]) {
- int m1[][] = {{2, 3, 4}, {5, 6, 7}}; // 2 X 3 matrix
- int m2[][] = {{1, 2}, {3, 4}, {5, 6}}; // 3 X 2 matrix
- int sum = 0; // initial sum value is 0
- int res[][] = new int[2][2]; // resultant matrix of 2 X 2
- for (int i = 0; i < 2; i++) { // i represent row
- for (int j = 0; j < 2; j++) { // j represent column
- res[i][j] = 0; // assume res[0][0] = 0
- for (int k = 0; k < 3; k++) {
- // k represent first matrix i.e. m1 -> number of column for // counter sum
- sum = sum + m1[i][k] * m2[k][j];
- }
- res[i][j] = sum; // assigned sum value to resultant matrix
- sum = 0; // reset to 0 for next iteration
- }
- }
- // printing the resultant matrix
- for (int i = 0; i < 2; i++) {
- for (int j = 0; j < 2; j++) {
- System.out.print(res[i][j] + " ");
- }
- System.out.println();
- }
- }
- }
Output:
31 40
58 76
Comments
Post a Comment