13,297,799 members (46,235 online)

#### Stats

18.4K views
7 bookmarked
Posted 14 Nov 2011

# la4j - Linear Algebra for Java

, 14 Nov 2011
Elegant and pure Java matrix library
 ```/* * Copyright 2011, Vladimir Kostyukov * * This file is part of la4j project (http://la4j.googlecode.com) * * 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. */ package la4j.linear; import la4j.err.LinearSystemException; import la4j.factory.Factory; import la4j.matrix.Matrix; import la4j.vector.Vector; public class GaussianSolver implements LinearSystemSolver { @Override public Vector solve(LinearSystem linearSystem, Factory factory) throws LinearSystemException { int rows = linearSystem.equations(); int columns = linearSystem.variables(); Matrix a = linearSystem.coefficientsMatrix().clone(); Vector b = linearSystem.rightHandVector().clone(); a.resize(rows, columns + 1); a.setColumn(columns, b); Matrix treangle = createExtendTriangleMatrix(a); return retraceGaus(treangle, factory); } private Matrix createExtendTriangleMatrix(Matrix matrix) throws LinearSystemException { Matrix result = matrix.clone(); for (int i = 0; i < result.rows(); i++) { int maxIndex = 0; double maxItem = result.get(i, i); for (int k = i + 1; k < result.rows(); k++) { if (Math.abs(result.get(k, i)) > maxItem) { maxItem = Math.abs(result.get(k, i)); maxIndex = k; } } if (Math.abs(maxItem) < EPS) throw new LinearSystemException("Linear system can not be solved."); if (maxIndex > i) result.swapRows(maxIndex, i); for (int j = i + 1; j < result.rows(); j++) { double C = result.get(j, i) / result.get(i, i); result.set(j, i, C); for (int k = i + 1; k < result.columns(); k++) { result.set(j, k, result.get(j, k) - result.get(i, k) * C); } } } return result; } private Vector retraceGaus(Matrix matrix, Factory factory) throws LinearSystemException { if (Math.abs(matrix.trace()) < EPS) { throw new LinearSystemException("Linear system has no solution."); } Vector result = factory.createVector(matrix.columns() - 1); for (int i = result.length() - 1; i >= 0; i--) { double summand = 0; for (int j = i + 1; j < result.length(); j++) { summand += result.get(j) * matrix.get(i, j); } result.set(i, (matrix.get(i, matrix.columns() - 1) - summand) / matrix.get(i, i)); } return result; } } ```

If a file you wish to view isn't highlighted, and is a text file (not binary), please let us know and we'll add colourisation support for it.