/* Copyright 2008 Tomasz Kaczmarzyk Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ final public class Matrix { private final int M; // number of rows private final int N; // number of columns private final float[][] data; // M-by-N array public int getWidth() { return N; } public int getHeight(){ return M; } public void setVal(int x, int y, float val) { data[x][y] = val; } public float getVal(int x, int y) { return data[x][y]; } // create M-by-N matrix of 0's public Matrix(int M, int N) { this.M = M; this.N = N; data = new float[M][N]; } // create matrix based on 2d array public Matrix(float[][] data) { M = data.length; N = data[0].length; this.data = new float[M][N]; for (int i = 0; i < M; i++) for (int j = 0; j < N; j++) this.data[i][j] = data[i][j]; } // copy constructor private Matrix(Matrix A) { this(A.data); } // create and return the transpose of the invoking matrix public Matrix transpose() { Matrix A = new Matrix(N, M); for (int i = 0; i < M; i++) for (int j = 0; j < N; j++) A.data[j][i] = this.data[i][j]; return A; } // return C = A + B public Matrix plus(Matrix B) { Matrix A = this; if (B.M != A.M || B.N != A.N) throw new RuntimeException("Illegal matrix dimensions."); Matrix C = new Matrix(M, N); for (int i = 0; i < M; i++) for (int j = 0; j < N; j++) C.data[i][j] = A.data[i][j] + B.data[i][j]; return C; } // return C = A - B public Matrix minus(Matrix B) { Matrix A = this; if (B.M != A.M || B.N != A.N) throw new RuntimeException("Illegal matrix dimensions."); Matrix C = new Matrix(M, N); for (int i = 0; i < M; i++) for (int j = 0; j < N; j++) C.data[i][j] = A.data[i][j] - B.data[i][j]; return C; } // does A = B exactly? public boolean eq(Matrix B) { Matrix A = this; if (B.M != A.M || B.N != A.N) throw new RuntimeException("Illegal matrix dimensions."); for (int i = 0; i < M; i++) for (int j = 0; j < N; j++) if (A.data[i][j] != B.data[i][j]) return false; return true; } // return C = A * B public Matrix times(Matrix B) { Matrix A = this; if (A.N != B.M) throw new RuntimeException("Illegal matrix dimensions."); Matrix C = new Matrix(A.M, B.N); for (int i = 0; i < C.M; i++) for (int j = 0; j < C.N; j++) for (int k = 0; k < A.N; k++) C.data[i][j] += (A.data[i][k] * B.data[k][j]); return C; } // print matrix to standard output public void show() { for (int i = 0; i < M; i++) { for (int j = 0; j < N; j++) System.out.print(data[i][j] + "\t" ); System.out.println(); } } }