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
According to me the code works perfectly fine !!
You may optimise the run time of the code using Strassen’s Matrix Multiplication.
Happy Coding !!
Online forums and learning are now in one easy-to-use experience.
By continuing, you accept the updated Community Terms of Use and acknowledge the Privacy Policy. Your public name, photo, and achievements may be publicly visible and available in search engines.
You must be a registered user to add a comment. If you've already registered, sign in. Otherwise, register and sign in.