Example usage for org.apache.commons.math3.linear Array2DRowRealMatrix subtract

List of usage examples for org.apache.commons.math3.linear Array2DRowRealMatrix subtract

Introduction

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

Prototype

public Array2DRowRealMatrix subtract(final Array2DRowRealMatrix m) throws MatrixDimensionMismatchException 

Source Link

Document

Returns this minus m .

Usage

From source file:org.drugis.mtc.yadas.MultivariateGaussian.java

public double compute(double[] x, double[] mu, double[][] sigma) {
    int d = x.length;
    if (d != mu.length || d != sigma.length) {
        throw new IllegalArgumentException("All arguments need to be of equal length");
    }/*from  w  w w . ja  va2 s. c  o m*/

    Array2DRowRealMatrix sigmaM = new Array2DRowRealMatrix(sigma);
    Array2DRowRealMatrix xM = new Array2DRowRealMatrix(x);
    Array2DRowRealMatrix muM = new Array2DRowRealMatrix(mu);

    // Return the log of:
    // 1/sqrt(2pi^d * det(sigma)) * e^(-.5 (x - mu)' inv(sigma) (x - mu))
    // Which is:
    // -log(sqrt(2pi^d * det(sigma))) + -.5 (x - mu)' inv(sigma) (x - mu) 
    Array2DRowRealMatrix dM = xM.subtract(muM);
    LUDecomposition sigmaD = new LUDecomposition(sigmaM, Precision.SAFE_MIN);
    try {
        RealMatrix sigmaInv = sigmaD.getSolver().getInverse();
        return -0.5 * (Math.log(2 * Math.PI) * d + Math.log(sigmaD.getDeterminant())
                + dM.transpose().multiply(sigmaInv).multiply(dM).getEntry(0, 0));
    } catch (RuntimeException e) {
        System.out.println(sigmaM);
        throw e;
    }
    /*      RealMatrix sigmaInv = sigmaM.inverse();
          return -0.5 * (
             Math.log(2 * Math.PI) * d + Math.log(sigmaM.getDeterminant()) +
             dM.transpose().multiply(sigmaInv).multiply(dM).getEntry(0, 0)); */
}