2018-07-16

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}}
  1. public class MatrixMultiplication {
  2.     public static void main(String args[]) {
  3.         int m1[][] = {{2, 3, 4}, {5, 6, 7}};    // 2 X 3 matrix
  4.         int m2[][] = {{1, 2}, {3, 4}, {5, 6}};  // 3 X 2 matrix
  5.         int res[][] = new int[2][2];    // resultant matrix of 2 X 2
  6.         for (int i = 0; i < 2; i++) {   // i represent row
  7.             for (int j = 0; j < 2; j++) {   // j represent column
  8.                 res[i][j] = 0;  // assume res[0][0] = 0
  9.                 for (int k = 0; k < 3; k++) {
  10.                     // k represent first matrix i.e. m1 -> number of column for                        // counter sum
  11.                     res[i][j] = res[i][j] + m1[i][k] * m2[k][j];
  12.                 }
  13.             }
  14.         }
  15.         // printing the resultant matrix
  16.         for (int i = 0; i < 2; i++) {
  17.             for (int j = 0; j < 2; j++) {
  18.                 System.out.print(res[i][j] + " ");
  19.             }
  20.             System.out.println();
  21.         }
  22.     }
  23. }
Method-II:
  1. public class MatrixMultiplication2D {
  2.     public static void main(String args[]) {
  3.         int m1[][] = {{2, 3, 4}, {5, 6, 7}};    // 2 X 3 matrix
  4.         int m2[][] = {{1, 2}, {3, 4}, {5, 6}};  // 3 X 2 matrix
  5.         int sum = 0;    // initial sum value is 0
  6.         int res[][] = new int[2][2];    // resultant matrix of 2 X 2
  7.         for (int i = 0; i < 2; i++) {   // i represent row
  8.             for (int j = 0; j < 2; j++) {   // j represent column
  9.                 res[i][j] = 0;  // assume res[0][0] = 0
  10.                 for (int k = 0; k < 3; k++) {
  11.                     // k represent first matrix i.e. m1 -> number of column for                        // counter sum
  12.                     sum = sum + m1[i][k] * m2[k][j];
  13.                 }
  14.                 res[i][j] = sum;    //  assigned sum value to resultant matrix
  15.                 sum = 0;    // reset to 0 for next iteration
  16.             }
  17.         }
  18.         // printing the resultant matrix
  19.         for (int i = 0; i < 2; i++) {
  20.             for (int j = 0; j < 2; j++) {
  21.                 System.out.print(res[i][j] + " ");
  22.             }
  23.             System.out.println();
  24.         }
  25.     }
  26. }
Output:
31 40
58 76

No comments:

Post a Comment