Skip to content

Instantly share code, notes, and snippets.

@moomoohk
Forked from anonymous/gist:7760387
Last active December 30, 2015 02:09
Show Gist options
  • Save moomoohk/7760436 to your computer and use it in GitHub Desktop.
Save moomoohk/7760436 to your computer and use it in GitHub Desktop.
// return C = A * B
public static double[][] multiply(double[][] A, double[][] B)
{
int mA = A.length; //row
int nA = A[0].length; //col
int mB = B.length;
int nB = A[0].length;
if (nA != mB)
throw new RuntimeException("Illegal matrix dimensions.");
double[][] C = new double[mA][nB];
for (int i = 0; i < mA; i++)
for (int j = 0; j < nB; j++)
for (int k = 0; k < nA; k++)
C[i][j] += (A[i][k] * B[k][j]);
return C;
}
public Matrix multiply(Matrix b)
{
if((rows()!=B.rows()) || (cols()!=B.cols()))
{
System.out.println("Error, cannot add since the 2 matrices do not have the same dimensions.");
System.exit(0);
}
Matrix c = new Matrix(rows(), cols());
for(int i = 1; i < rows(); i++)
for(int j = 1; j < b.rows(); j++)
for(int k = 1; k < cols(); k++)
c.set(i, j, c.get(i, j) + get(i, k) * b.get(k, j));
return c;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment