Forums

Articles
Create
cancel
Showing results for 
Search instead for 
Did you mean: 

Java Matrix Multiplication

Vikash Jain
I'm New Here
I'm New Here
Those new to the Atlassian Community have posted less than three times. Give them a warm welcome!
October 28, 2021

Hi All,

Need help to understand if the code below for Matrix Multiplication is Correct. I was reading the blog and was a bit confused. If this is correct please tell me this will save my assignment.


import java.util.Scanner;

public class MatrixMultiplicationExample{
public static void main(String args[]){

int row1, col1, row2, col2;
Scanner s = new Scanner(System.in);
System.out.print("Enter number of rows in first matrix:");
row1 = s.nextInt();
System.out.print("Enter number of columns in first matrix:");
col1 = s.nextInt();
System.out.print("Enter number of rows in second matrix:");
row2 = s.nextInt();
System.out.print("Enter number of columns in second matrix:");
col2 = s.nextInt();

if (col1 != row2) {
System.out.println("Matrix multiplication is not possible");
}
else {
int a[][] = new int[row1][col1];
int b[][] = new int[row2][col2];
int c[][] = new int[row1][col2];

System.out.println("Enter values for matrix A : \n");
for (int i = 0; i < row1; i++) {
for (int j = 0; j < col1; j++)
a[i][j] = s.nextInt();
}
System.out.println("Enter values for matrix B : \n");
for (int i = 0; i < row2; i++) {
for (int j = 0; j < col2; j++)
b[i][j] = s.nextInt();
}

System.out.println("Matrix multiplication is : \n");
for(int i = 0; i < row1; i++) {
for(int j = 0; j < col2; j++){
c[i][j]=0;
for(int k = 0; k < col1; k++){
c[i][j] += a[i][k] * b[k][j];
}
System.out.print(c[i][j] + " ");
}
System.out.println();
}
}
}
}


The code is taken from here 

1 answer

Suggest an answer

Log in or Sign up to answer
0 votes
Harshavardhan Bajoria
Contributor
October 28, 2021

According to me the code works perfectly fine !!

You may optimise the run time of the code using Strassen’s Matrix Multiplication. 

Happy Coding !! 

TAGS
AUG Leaders

Atlassian Community Events