Come for the products,
stay for the community

The Atlassian Community can help you and your team get more value out of Atlassian products and practices.

Atlassian Community about banner
4,365,459
Community Members
 
Community Events
168
Community Groups

Java Matrix Multiplication

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

According to me the code works perfectly fine !!

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

Happy Coding !! 

Suggest an answer

Log in or Sign up to answer
TAGS

Atlassian Community Events