日期:2014-05-20 浏览次数:21020 次
class Matrix {
int rows;
int cols;
double data[][];
public Matrix() {
}
public Matrix(int rows, int cols) {
this.rows = rows;
this.cols = cols;
data = new double[rows][cols];
}
public Matrix(int rows, int cols, double data[][]) {
this.rows = rows;
this.cols = cols;
this.data = data;
}
double getData(int row, int col) {
return data[row][col];
}
void setData(int row, int col, double value) {
this.data[row][col] = value;
}
public double[][] multiply(Matrix m) {
Matrix n = new Matrix();
n.data = new double[m.rows][this.cols];
for (int i = 0; i < m.rows; i++) {
for (int j = 0; j < this.cols; j++) {
n.data[i][j] = 0;
for (int k = 0; k < m.cols; k++)
n.data[i][j] += m.data[i][k] * this.data[k][j];
}
}
return n.data;
}
void print(Matrix n) {
for (int i = 0; i < n.rows; i++) {
for (int j = 0; j < n.cols; j++) {
System.out.print(n.data[i][j] + "\t");
}
System.out.println();
}
}
}
public class MatrixTest
{
public static void main(String[] args) {
Matrix x = new Matrix(3, 3);
for (int i = 0; i < x.rows; i++)
for (int j = 0; j < x.cols; j++) {
x.setData(i, j, (i + 1) * (j + 2));
}
double b[][] = { { 1, 5, 2, 8 }, { 5, 9, 10, -3 }, { 2, 7, -5, -18 } };
Matrix y = new Matrix(b.length, b[0].length, b);
double d[][] = y.multiply(x);
Matrix k = new Matrix(d.length, d[0].length, d);
y.print(k);
}
}