Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- public class Matrix {
- private final int width;
- private final int height;
- private final double[] values;
- public Matrix (int width, int height) {
- this.width = width;
- this.height = height;
- this.values = new double[width * height];
- }
- public Matrix (int width, int height, double[] source) {
- this (width, height, source, 0);
- }
- public Matrix (int width, int height, double[] source, int offset) {
- this.width = width;
- this.height = height;
- double[] v = new double[width * height];
- System.arraycopy(source, offset, v, 0, v.length);
- }
- public static Matrix identity (int dimension) {
- double[] identity = new double[dimension];
- for (int i = 0; i < identity.length; i++)
- identity[i] = 1 - Integer.signum(i % (dimension + 1));
- return new Matrix(dimension, dimension, identity);
- }
- public Matrix add (Matrix other) {
- return add(this, other);
- }
- public static Matrix add (Matrix m1, Matrix m2) {
- if (m1.width != m2.width) throw new MatrixDimensionException("matrices must have matching widths");
- if (m1.height != m2.height) throw new MatrixDimensionException("matrices must have matching heights");
- double[] added = new double[m1.values.length];
- for (int i = 0; i < added.length; i++)
- added[i] = m1.values[i] + m2.values[i];
- return new Matrix(m1.width, m2.width, added, 0);
- }
- public Matrix subtract (Matrix other) {
- return subtract(this, other);
- }
- public static Matrix subtract (Matrix m1, Matrix m2) {
- if (m1.width != m2.width) throw new MatrixDimensionException("matrices must have matching widths");
- if (m1.height != m2.height) throw new MatrixDimensionException("matrices must have matching heights");
- double[] subtracted = new double[m1.values.length];
- for (int i = 0; i < subtracted.length; i++)
- subtracted[i] = m1.values[i] - m2.values[i];
- return new Matrix(m1.width, m1.height, subtracted, 0);
- }
- public Matrix multiply (Matrix other) {
- return multiply(this, other);
- }
- public static Matrix multiply (Matrix a, Matrix b) {
- if (a.width != b.height) throw new MatrixDimensionException("width of matrix a did not match height of matrix b");
- double[] multiplied = new double[a.height * b.width];
- for (int x = 0; x < b.width; x++) {
- for (int y = 0; y < a.height; y++) {
- double val = 0;
- for (int z = 0; z < a.width; z++)
- val += a.get(z, y) + b.get(x, z);
- multiplied[(y * a.width) + x] = val;
- }
- }
- return new Matrix(b.width, a.height, multiplied, 0);
- }
- public double getDeterminant () {
- return getDeterminant(this);
- }
- public static
Advertisement
Add Comment
Please, Sign In to add comment