Example usage for org.apache.commons.math3.linear RealVector mapAddToSelf

List of usage examples for org.apache.commons.math3.linear RealVector mapAddToSelf

Introduction

In this page you can find the example usage for org.apache.commons.math3.linear RealVector mapAddToSelf.

Prototype

public RealVector mapAddToSelf(double d) 

Source Link

Document

Add a value to each entry.

Usage

From source file:ellipsoidFit.FitPoints.java

/**
 * Solve the polynomial expression Ax^2 + By^2 + Cz^2 + 2Dxy + 2Exz + 2Fyz +
 * 2Gx + 2Hy + 2Iz from the provided points.
 * /*  w  ww.  j  a  va2s  .  com*/
 * @param points
 *            the points that will be fit to the polynomial expression.
 * @return the solution vector to the polynomial expression.
 */
private RealVector solveSystem(ArrayList<ThreeSpacePoint> points) {
    // determine the number of points
    int numPoints = points.size();

    // the design matrix
    // size: numPoints x 9
    RealMatrix d = new Array2DRowRealMatrix(numPoints, 9);

    // Fit the ellipsoid in the form of
    // Ax^2 + By^2 + Cz^2 + 2Dxy + 2Exz + 2Fyz + 2Gx + 2Hy + 2Iz
    for (int i = 0; i < d.getRowDimension(); i++) {
        double xx = Math.pow(points.get(i).x, 2);
        double yy = Math.pow(points.get(i).y, 2);
        double zz = Math.pow(points.get(i).z, 2);
        double xy = 2 * (points.get(i).x * points.get(i).y);
        double xz = 2 * (points.get(i).x * points.get(i).z);
        double yz = 2 * (points.get(i).y * points.get(i).z);
        double x = 2 * points.get(i).x;
        double y = 2 * points.get(i).y;
        double z = 2 * points.get(i).z;

        d.setEntry(i, 0, xx);
        d.setEntry(i, 1, yy);
        d.setEntry(i, 2, zz);
        d.setEntry(i, 3, xy);
        d.setEntry(i, 4, xz);
        d.setEntry(i, 5, yz);
        d.setEntry(i, 6, x);
        d.setEntry(i, 7, y);
        d.setEntry(i, 8, z);
    }

    // solve the normal system of equations
    // v = (( d' * d )^-1) * ( d' * ones.mapAddToSelf(1));

    // Multiply: d' * d
    RealMatrix dtd = d.transpose().multiply(d);

    // Create a vector of ones.
    RealVector ones = new ArrayRealVector(numPoints);
    ones.mapAddToSelf(1);

    // Multiply: d' * ones.mapAddToSelf(1)
    RealVector dtOnes = d.transpose().operate(ones);

    // Find ( d' * d )^-1
    DecompositionSolver solver = new SingularValueDecomposition(dtd).getSolver();
    RealMatrix dtdi = solver.getInverse();

    // v = (( d' * d )^-1) * ( d' * ones.mapAddToSelf(1));
    RealVector v = dtdi.operate(dtOnes);

    return v;
}