[code="java"]public class Matrix {
int rows;
int cols;
double data[][];
public Matrix() {
this(0, 0);
}
public Matrix(int rows, int cols) {
this(rows, cols, new double[rows][cols]);
}
public Matrix(int rows, int cols, double[][] data) {
super();
this.rows = rows;
this.cols = cols;
this.data = data;
}
public double getData(int row, int col) {
return data[row][col];
}
public void setData(int row, int col, double value) {
data[row][col] = value;
}
public double[][] multiply(double[][] m2) {
int m1rows = data.length;
int m1cols = data[0].length;
int m2rows = m2.length;
int m2cols = m2[0].length;
if (m1cols != m2rows)
throw new IllegalArgumentException("matrix doesn't match");
double[][] result = new double[m1rows][m2cols];
// multiply
for (int i = 0; i < m1rows; i++)
for (int j = 0; j < m2cols; j++)
for (int k = 0; k < m1cols; k++)
result[i][j] += data[i][k] * m2[k][j];
return result;
}
public String toString() {
StringBuffer sb = new StringBuffer();
int rows = data.length;
int cols = data[0].length;
sb.append("array[" + rows + "][" + cols + "] = " + "\n");
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++)
sb.append(" " + data[i][j] + " ");
sb.append("\n");
}
sb.append("\n");
return sb.toString();
}
public static void main(String[] argv) {
double x[][] = { { 3, 2, 3 }, { 5, 9, 8 }, };
Matrix m = new Matrix(3, 2, x);
double y[][] = { { 4, 7 }, { 9, 3 }, { 8, 1 }, };
double z[][] = m.multiply(y);
Matrix zm = new Matrix(z.length, z[0].length, z);
// print result
System.out.println(zm);
}
}[/code]