How to Multiply Two Matrices inwards Java

I kickoff learned nigh matrix inward shape twelfth too I kickoff wrote the plan to multiply 2 matrices on my kickoff semester of engineering, so, when I idea nigh this program, It brings a lot of memories from the past. It's genuinely a beginner do to prepare coding logic, much similar Fibonacci, prime, too palindrome check, but what brand this plan interesting is the locomote of the two-dimensional array to stand upwards for a matrix inward Java.  Since matrix has both rows too columns, two-dimensional array only naturally fits into the requirement. Another of import matter to solve this work is to recall the dominion of matrix multiplication inward mathematics. If you lot don't recall the rule, only forget nigh how to solve this problem, unless you lot get got access to Google. So, first, we'll refresh the rules of multiplication too so we'll hold off into coding aspect.

Influenza A virus subtype H5N1 Matrix is cipher but a two-dimensional array of numbers. It has rows too columns, for illustration next matrix has 2 rows too iii columns
[2, 4, 6]
[1, 3, 5]

To multiply a matrix past times a unmarried publish is easy, only multiply each chemical gene of a matrix alongside that publish is known a scalar multiplication.

For example, if you lot multiple higher upwards matrix alongside 2 hither is how the matrix multiplication volition work

Matrix Multiply Constant

These are the calculations:
2×2=8 2×4=8 2x6=12
2×1=2 2×3=6 2x5=10

We telephone telephone the publish ("2" inward this case) a scalar, so this is called "scalar multiplication", but that's non what you lot volition larn here. In this program, you lot volition larn nigh how to multiply i matrix to only about other using array inward Java.




Multiplying i matrix to only about other matrix

In lodge to multiply 2 matrices, you lot require to calculate the point production or rows too columns. The "Dot Product" is where nosotros multiply matching members, so total up:

(1, 2, 3) • (7, 9, 11) = 1×7 + 2×9 + 3×11 = 58

We jibe the 1st members (1 too 7), multiply them, likewise for the 2nd members (2 too 9) too the tertiary members (3 too 11), too lastly total them up.

There are every bit good 2 rules of matrix multiplication which you lot require to remember:
  • The publish of columns of the kickoff matrix must live equal to the publish of rows of the instant matrix. For example, if the kickoff matrix has 2 columns so you lot tin hand the sack multiply it alongside only about other matrix which has 2 rows. 
  • The production matrix volition get got the same publish of rows every bit the kickoff matrix, too the same publish of columns every bit the instant matrix.

Here is a dainty diagram which explains matrix multiplication beautifully alongside an example:

th too I kickoff wrote the plan to multiply 2 matrices on my kickoff semester of engineer How to Multiply Two Matrices inward Java



Java Program to multiply 2 matrices inward Java

Here is our consummate Java plan to multiply i matrix alongside only about other inward Java. In this program, nosotros get got a Matrix shape which has rows too columns too holds the matrix numbers into a two-dimensional array. The Matrix shape every bit good get got read() method to read user input using Scanner too populate the matrix. It every bit good has a multiply(Matrix other) method to perform the multiplication of this matrix alongside given matrix too returns a novel Matrix whose values are equal to the production of 2 matrices.  It every bit good has a impress method to nicely impress the matrix into the ascendance prompt.

The multiply(Matrix other) method every bit good does only about pre-validation every bit per the rules of matrix multiplication e.g. it checks if rows of given Matrix is equal to the column of this matrix or not, if they are non equal so matrix multiplication cannot live performed, thus it throw java.lang.IllegalArgumetnException.  See Clean Code to larn to a greater extent than nigh pre-validation inward methods.

import java.util.Scanner;  /*  * Java Program to multiply 2 matrices  */ public class MatricsMultiplicationProgram {    public static void main(String[] args) {      System.out         .println("Welcome to Java plan to calcualte multiplicate of 2 matrices");     Scanner scnr = new Scanner(System.in);      System.out.println("Please locomote inward details of kickoff matrix");     System.out.print("Please Enter publish of rows: ");     int row1 = scnr.nextInt();     System.out.print("Please Enter publish of columns: ");     int column1 = scnr.nextInt();     System.out.println();     System.out.println("Enter kickoff matrix elements");     Matrix first = new Matrix(row1, column1);     first.read();      System.out.println("Please locomote inward details of instant matrix");     System.out.print("Please Enter publish of rows: ");     int row2 = scnr.nextInt();     System.out.print("Please Enter publish of columns: ");     int column2 = scnr.nextInt();     System.out.println();     System.out.println("Enter instant matrix elements");      Matrix instant = new Matrix(row2, column2);     second.read();      Matrix production = first.multiply(second);      System.out.println("first matrix: ");     first.print();     System.out.println("second matrix: ");     second.print();     System.out.println("product of 2 matrices is:");     product.print();      scnr.close();    }  }  /*  * Java shape to stand upwards for a Matrix. It uses a 2 dimensional array to  * stand upwards for a Matrix.  */ class Matrix {   private int rows;   private int columns;   private int[][] data;    public Matrix(int row, int column) {     this.rows = row;     this.columns = column;     data = new int[rows][columns];   }    public Matrix(int[][] data) {     this.data = data;     this.rows = data.length;     this.columns = data[0].length;   }    public int getRows() {     return rows;   }    public int getColumns() {     return columns;   }    /**    * fills matrix from information entered past times user inward console    *     * @param rows    * @param columns    */   public void read() {     Scanner s = new Scanner(System.in);     for (int i = 0; i < rows; i++) {       for (int j = 0; j < columns; j++) {         data[i][j] = s.nextInt();       }     }    }    /**    *     * @param a    * @param b    * @return    */   public Matrix multiply(Matrix other) {     if (this.columns != other.rows) {       throw new IllegalArgumentException(           "column of this matrix is non equal to row "               + "of instant matrix, cannot multiply");     }      int[][] production = new int[this.rows][other.columns];     int total = 0;     for (int i = 0; i < this.rows; i++) {       for (int j = 0; j < other.columns; j++) {         for (int k = 0; k < other.rows; k++) {           total = total + data[i][k] * other.data[k][j];         }         product[i][j] = sum;       }     }     return new Matrix(product);   }    /**    *     * @param matrix    */   public void print() {     for (int i = 0; i < rows; i++) {       for (int j = 0; j < columns; j++) {         System.out.print(data[i][j] + " ");       }       System.out.println();     }   }  }  Output: Welcome to Java plan to calculate multiplicate of 2 matrices Please enter details of the first matrix Please Enter publish of rows: 2 Please Enter publish of columns: 2  Enter first matrix elements 1 2 3 4 Please enter details of the instant matrix Please Enter publish of rows: 2 Please Enter publish of columns: 2  Enter instant matrix elements 1 2 2 2 first matrix:  1 2  3 4  instant matrix:  1 2  2 2  production of 2 matrices is: 5 11  22 36 


That's all nigh how to write a Java plan to multiply 2 matrices. You tin hand the sack locomote this plan for trying too testing. You should fifty-fifty attempt to write JUnit attempt out for this plan to cheque diverse boundary conditions. If you lot don't know how to write Junit attempt out cases inward Java so delight refer to JUnit inward Action or Test Driven, a TDD too credence TDD guide for Java developers. These exercises volition attention you lot to laid upwards your programming logic too every bit good attention you lot to empathise when too how to locomote information construction piece solving problems.


Other Java Programming exercises for beginners
  • How to implement binary search using recursion inward Java? (solution)
  • How to calculate the average of all numbers of an array inward Java? (program)
  • How to implement Linear Search inward Java? (solution)
  • How to calculate the foursquare origin of a given publish inward Java? (solution)
  • How to calculate Area of Triangle inward Java? (program)
  • How to uncovering all permutations of a given String inward Java? (solution)
  • How to remove duplicate elements from the array inward Java? (solution)
  • How to cheque if 2 given Strings are Anagram inward Java? (solution)
  • How to impress Fibonacci serial inward Java (solution)
  • How to cheque if a twelvemonth is a outpouring twelvemonth inward Java? (solution)
  • How to contrary a String inward house inward Java? (solution)
  • How to cheque if given publish is prime number inward Java (solution)
  • How to uncovering the highest occurring give-and-take from a given file in Java? (solution)
  • How to count vowels too consonants inward given String inward Java? (solution)
  • How to cheque if given String is palindrome or non inward Java? (solution)
  • How to take duplicate characters from String inward Java? (solution)
  • How to cheque if a String contains duplicate characters inward Java? (solution)
  • How to contrary words inward a given String inward Java? (solution)
  • How to calculate the total of all elements of an array inward Java? (program)
  • How to cheque if 2 rectangles intersect alongside each other inward Java? (solution)
  • How to contrary an array inward house inward Java? (solution)
  • How to uncovering if given Integer is Palindrome inward Java? (solution)

References
Matrix Multiplication Wikipedia
Multiplying Matrices Khan Academy


Subscribe to receive free email updates:

0 Response to "How to Multiply Two Matrices inwards Java"

Posting Komentar