/////// Matrix.java /////// package matrix; public class Matrix { public Matrix(int r, int c) { if ( r > 0 && c > 0 ) mat = new double[nr=r][nc=c]; else { mat = null; nr=nc=0; } } public Matrix(double[][] m) { mat = m; nr = m.length; nc = m[0].length; } protected Matrix() { } public double element(int i, int j) throws InvalidIndexException { if ( i < 0 || j < 0 || i >= nr || j >= nc ) throw new InvalidIndexException( "Matrix element(" + i + "," + j + ")" ); return mat[i][j]; } public void element(int i, int j, double e) throws InvalidIndexException { if ( i < 0 || j < 0 || i >= nr || j >= nc ) throw new InvalidIndexException( "Matrix element(" + i + "," + j + "," + e + ")" ); mat[i][j] = e; } public int rows() { return nr; } public int cols() { return nc; } public Matrix times(Matrix b) throws MatrixException { if ( nc != b.nr ) throw new IncompatibleDimException( "Matrix times: "+ nr+"X"+nc + " and " + b.nr+"X"+b.nc); Matrix p = new Matrix(nr,b.nc); for (int i=0 ; i < nr ; i++) { for (int j=0 ; j < b.nc; j++) p.element(i,j, rowTimesCol(i, b.mat, j)); } return(p); } public String toString() { StringBuffer buf = new StringBuffer(); for (int i = 0; i < nr; i++) { buf.append("( "); for (int j = 0; j < nc-1; j++) { buf.append(mat[i][j]); buf.append(" "); } buf.append(mat[i][nc-1]); buf.append(" )\n"); } buf.setLength(buf.length()-1); return new String(buf); } private double rowTimesCol(int ri, double[][] b, int ci) { double sum=0.0d; double[] row = mat[ri]; for (int k=0; k < b.length; k++) sum += row[k] * b[k][ci]; return(sum); } private double[][] mat; // the matrix private int nr, nc; // rows and cols }