Skip to content

Instantly share code, notes, and snippets.

@timmolderez
Created December 17, 2015 00:47
Show Gist options
  • Save timmolderez/98e852661165a0dd8289 to your computer and use it in GitHub Desktop.
Save timmolderez/98e852661165a0dd8289 to your computer and use it in GitHub Desktop.
package test;
public class Matrix {
public static double[][] random(int m, int n) {
double[][] C = new double[m][n];
for (int i = 0; i < m; i++)
for (int j = 0; j < n; j++)
C[i][j] = Math.random();
return C;
}
public static double[][] identity(int n) {
double[][] I = new double[n][n];
for (int i = 0; i < n; i++)
I[i][i] = 1;
return I;
}
public static double[][] transpose(double[][] A) {
int m = A.length;
int n = A[0].length;
double[][] C = new double[n][m];
for (int i = 0; i < m; i++)
for (int j = 0; j < n; j++)
C[j][i] = A[i][j];
return C;
}
public static double[][] add(double[][] A, double[][] B) {
int m = A.length;
int n = A[0].length;
double[][] C = new double[m][n];
for (int i = 0; i < m; i++)
for (int j = 0; j < n; j++)
C[i][j] = A[i][j] + B[i][j];
return C;
}
public static double[][] subtract(double[][] A, double[][] B) {
int m = A.length;
int n = A[0].length;
double[][] C = new double[m][n];
for (int i = 0; i < m; i++)
for (int j = 0; j < n; j++)
C[i][j] = A[i][j] - B[i][j];
return C;
}
public static double[][] multiply(double[][] A, double[][] B) {
int mA = A.length;
int nA = A[0].length;
int mB = B.length;
int nB = B[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 static void print(double[][] x) {
int m = x.length;
int n = x[0].length;
for (int i = 0; i < m; i++) {
System.out.print("[ ");
for (int j = 0; j < n; j++) {
System.out.print(String.format( "%.2f", x[i][j]) + " ");
}
System.out.println("]");
}
}
public static void main(String[] args) {
double[][] d = { { 1, 2, 3 }, { 4, 5, 6 }, { 9, 1, 3} };
double[][] c = Matrix.identity(5);
double[][] a = Matrix.random(5, 5);
double[][] b = Matrix.transpose(a);
double[][] e = Matrix.add(a, b);
print(a);
System.out.println("---");
print(b);
System.out.println("--- Multiplication: ");
double[][] f = Matrix.multiply(a, b);
print(f);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment