Answers for "matrix mulitplication in java"

4

multiply matrices java

public class Matrix {
  private double[][] multiply(double[][] matrixOne, double[][] matrixTwo) {
            assert matrixOne[0].length == matrixTwo.length: "width of matrix one must be equal to height of matrix two";
            double[][] product = new double[matrixOne.length][matrixTwo[0].length];
    		//fills output matrix with 0's
            for(short l = 0; l<matrixOne.length; l++) {
                for(short m = 0; m<matrixTwo[0].length; m++) {
                    product[l][m] = 0;
                }
            }
    		//takes the dot product of the rows and columns and adds them to output matrix
            for(short i = 0; i<matrixOne.length; i++) {
                for(short j = 0; j<matrixTwo[0].length; j++) {
                    for(short k = 0; k<matrixOne[0].length; k++) {
                        product[i][j] += matrixOne[i][k] * matrixTwo[k][j];
                    }
                }
            }
            return product;
        }
}
Posted by: Guest on November-18-2020
0

Matrix multiplication in java using function

// matrix multiplication java
public class MatrixMultiplicationJavaDemo 
{
   public static int[][] multiplyMatrix(int[][] matrix1, int[][] matrix2, int row, int column, int col)
   {
      int[][] multiply = new int[row][col];
      for(int a = 0; a < row; a++) 
      {
         for(int b = 0; b < col; b++) 
         {
            for(int k = 0; k < column; k++) 
            {
               multiply[a][b] += matrix1[a][k] * matrix2[k][b];
            }
         }
      }
      return multiply;
   }
   public static void printMatrix(int[][] multiply) 
   {
      System.out.println("Multiplication of two matrices: ");
      for(int[] row : multiply) 
      {
         for(int column : row) 
         {
            System.out.print(column + "    ");
         }
         System.out.println();
      }
   }
   public static void main(String[] args) 
   {
      int row = 2, col = 3;
      int column = 2;
      int[][] matrixOne = {{1, 2, 3}, {4, 5, 6}};
      int[][] matrixTwo = {{7, 8}, {9, 1}, {2, 3}};
      int[][] product = multiplyMatrix(matrixOne, matrixTwo, row, col, column);
      printMatrix(product);
   }
}
Posted by: Guest on November-25-2020

Code answers related to "Java"

Java Answers by Framework

Browse Popular Code Answers by Language