Answers for "how to do matrix multiplication 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

public class MatrixMultiplicationExample{  
    public static void main(String args[]){  
    //creating two matrices    
    int a[][]={{1,1,1},{2,2,2},{3,3,3}};    
    int b[][]={{1,1,1},{2,2,2},{3,3,3}};    
        
    //creating another matrix to store the multiplication of two matrices    
    int c[][]=new int[3][3];  //3 rows and 3 columns  
        
    //multiplying and printing multiplication of 2 matrices    
    for(int i=0;i<3;i++){    
    for(int j=0;j<3;j++){    
    c[i][j]=0;      
    for(int k=0;k<3;k++)      
    {      
    c[i][j]+=a[i][k]*b[k][j];      
    }//end of k loop  
    System.out.print(c[i][j]+" ");  //printing matrix element  
    }//end of j loop  
    System.out.println();//new line    
    }    
    }}
Posted by: Guest on September-14-2020

Code answers related to "how to do matrix multiplication in java"

Code answers related to "Java"

Java Answers by Framework

Browse Popular Code Answers by Language