Skip to content

Instantly share code, notes, and snippets.

@MaximeD
Created October 31, 2012 12:03
Show Gist options
  • Save MaximeD/3986691 to your computer and use it in GitHub Desktop.
Save MaximeD/3986691 to your computer and use it in GitHub Desktop.
Compute the matrix multiplication of two matrices
class prod_mat {
public static void main(String[] args) {
int [][] a = {
{5,1},
{2,3},
{3,4}
};
int [][] b = {
{1,2,0},
{4,3,-1}
};
// a is a matrix of type (m,n)
// b is a matrix of type (n,p)
int m = a.length;
if (a[0].length != b.length)
throw new Error("Les deux matrices ne sont pas compatibles !");
int n = a[0].length;
int p = b[0].length;
// c hold the matrix multiplication
// so c is of type (m,p)
int [][] c = new int[m][p];
int i,j,k;
int prod;
for (k=0; k<n; k++) {
for (i=0; i<m; i++) {
for (j=0; j<p; j++) {
c[i][j] += a[i][k] * b[k][j];
}
}
}
// display result
for (i=0; i<m; i++) {
for (j=0; j<p; j++) {
System.out.print(c[i][j] + " ");
}
System.out.println();
}
}
}
@oelmekki
Copy link

haha

@MaximeD
Copy link
Author

MaximeD commented Nov 4, 2012

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment