Example usage for org.apache.commons.math.linear RealMatrix multiply

List of usage examples for org.apache.commons.math.linear RealMatrix multiply

Introduction

In this page you can find the example usage for org.apache.commons.math.linear RealMatrix multiply.

Prototype

RealMatrix multiply(RealMatrix m) throws IllegalArgumentException;

Source Link

Document

Returns the result of postmultiplying this by m.

Usage

From source file:math2605.gn_exp.java

private static RealMatrix findQR(RealMatrix J, RealMatrix r) {
    qr_fact_househ m = new qr_fact_househ(J);
    RealMatrix Q = m.getQ();//from  w  ww.j  a va 2 s .  c  om
    RealMatrix qTranspose = Q.transpose();
    System.out.println("qtranspose");
    System.out.println(qTranspose);
    RealMatrix R = m.getR();
    MatrixMethods temp = new MatrixMethods(R);
    RealMatrix rInverse = temp.inverseMatrix();
    System.out.println("rInverse");
    System.out.println(rInverse);
    RealMatrix sub = rInverse.multiply(qTranspose).multiply(r);
    return sub;
}

From source file:math2605.qr_fact_givens.java

public qr_fact_givens(RealMatrix A) {
    int m = A.getRowDimension();
    int n = A.getColumnDimension();
    R = A.copy();//w ww. ja va 2s  .c  o  m
    RealMatrix a = A.copy();
    Q = null;
    boolean firstQ = true;
    for (int j = 0; j < n; j++) {
        int row = j;
        for (int i = j; i < m - 1; i++) {
            if (a.getEntry(row, j) == 0) {
                //System.out.println("in break");
                break;
            }
            if (upperTriangular(a)) {
                //System.out.println("is ut");
                continue;
            }

            double[] cs = new double[2];

            cs = givensRoatation(a.getEntry(i, j), a.getEntry(i + 1, j));
            RealMatrix G = createG(i, i + 1, cs, n);
            R = G.multiply(R);
            if (firstQ) {
                Q = G.transpose();
                firstQ = false;
            } else {
                Q = Q.multiply(G.transpose());
            }
            a = G.multiply(a);
            row++;
        }
    }
}

From source file:dr.math.Procrustes.java

/**
 * procrustinate a single set of coordinates
 * @param X/*from   w w  w  .  ja  va2 s.c  o m*/
 */
public double[] procrustinate(double[] X) {
    if (X.length != columnDimension) {
        throw new IllegalArgumentException("X does not have the expected number of elements");
    }

    RealMatrix tmp = new Array2DRowRealMatrix(X);

    // rotate, scale and translate
    RealMatrix Xnew = tmp.multiply(R).scalarMultiply(s).add(T);

    return Xnew.getRow(0);
}

From source file:com.opengamma.analytics.math.matrix.CommonsMatrixAlgebra.java

/**
 * {@inheritDoc}//ww w  . ja va  2  s. co m
 * The following combinations of input matrices m1 and m2 are allowed:
 * <ul>
 * <li> m1 = 2-D matrix, m2 = 2-D matrix, returns $\mathbf{C} = \mathbf{AB}$
 * <li> m1 = 2-D matrix, m2 = 1-D matrix, returns $\mathbf{C} = \mathbf{A}b$
 * </ul>
 */
@Override
public Matrix<?> multiply(final Matrix<?> m1, final Matrix<?> m2) {
    Validate.notNull(m1, "m1");
    Validate.notNull(m2, "m2");
    Validate.isTrue(!(m1 instanceof DoubleMatrix1D), "Cannot have 1D matrix as first argument");
    if (m1 instanceof DoubleMatrix2D) {
        final RealMatrix t1 = CommonsMathWrapper.wrap((DoubleMatrix2D) m1);
        RealMatrix t2;
        if (m2 instanceof DoubleMatrix1D) {
            t2 = CommonsMathWrapper.wrapAsMatrix((DoubleMatrix1D) m2);
        } else if (m2 instanceof DoubleMatrix2D) {
            t2 = CommonsMathWrapper.wrap((DoubleMatrix2D) m2);
        } else {
            throw new IllegalArgumentException("Can only have 1D or 2D matrix as second argument");
        }
        return CommonsMathWrapper.unwrap(t1.multiply(t2));
    }
    throw new IllegalArgumentException("Can only multiply 2D and 1D matrices");
}

From source file:dr.math.Procrustes.java

/**
 * procrustinate the complete matrix of coordinates
 * @param X the matrix containing coordinates (same dimensions as X in the constructor)
 * @return the transformed matrix/*  ww w  .  j  a  va2  s  .c o  m*/
 */
public final RealMatrix procrustinate(RealMatrix X) {
    if (X.getRowDimension() != rowDimension) {
        throw new IllegalArgumentException("X does not have the expected number of rows");
    }
    if (X.getColumnDimension() != columnDimension) {
        throw new IllegalArgumentException("X does not have the expected number of columns");
    }

    //       X.new <- s * X %*% R + matrix(tt, nrow(X), ncol(X), byrow = TRUE)
    RealMatrix tt = new Array2DRowRealMatrix(rowDimension, columnDimension);

    for (int i = 0; i < rowDimension; i++) {
        tt.setRowMatrix(i, T.transpose());
    }

    // rotate, scale and translate
    return X.multiply(R).scalarMultiply(s).add(tt); // Was a bug here
}

From source file:lib.regressions.MultipleRegression.java

/**
 * Perform the regression computations//from   www  .j a  v  a 2  s  . c om
 */
private void compute() {
    // Set everything to 0.
    for (int i = 0; i < (myNumVar + 1); i++) {
        myCoef[i] = 0.0;
        myStdErr[i] = 0.0;
        myTStat[i] = 0.0;
    }
    myChiSq = 0.0;
    myRSq = 0.0;
    myAdjustedRSq = 0.0;

    // Set coefficients, t-stat, etc. if there has been enough data added.
    if (myCount >= (myNumVar + 1)) {
        RealMatrix dataMatrix = new RealMatrixImpl(mySums.getSumXX());
        RealMatrix xxMatrix = dataMatrix.getSubMatrix(1, myNumVar + 1, 1, myNumVar + 1);
        RealMatrix xyMatrix = dataMatrix.getSubMatrix(1, myNumVar + 1, 0, 0);

        computeOkX(); // Determine which X components to use.
        int[] listX = getListX();
        int[] listY = { 0 };
        int numX = listX.length;
        RealMatrix xxSubMatrix = xxMatrix.getSubMatrix(listX, listX);
        RealMatrix xySubMatrix = xyMatrix.getSubMatrix(listX, listY);

        double sumY = mySums.getSumXX()[0][1];
        double sumYY = mySums.getSumXX()[0][0];

        if (!xxSubMatrix.isSingular()) {
            RealMatrix xxInverse = xxSubMatrix.inverse();
            RealMatrix coefMatrix = xxInverse.multiply(xySubMatrix);
            double[] coef = coefMatrix.getColumn(0);

            // Compute chi-squared
            myChiSq = sumYY - 2 * coefMatrix.transpose().multiply(xySubMatrix).getEntry(0, 0)
                    + +coefMatrix.transpose().multiply(xxSubMatrix).multiply(coefMatrix).getEntry(0, 0);

            // Compute R^2 and adjusted R^2
            int offset = getUseIntercept() ? 1 : 0;
            myRSq = 1.0 - myChiSq / (sumYY - sumY * sumY / myCount);
            myAdjustedRSq = 1 - ((1 - myRSq) * (myCount - 1) + 1 - offset) / (myCount - numX);

            // Compute standard errors and t-stats
            int j = 0;
            for (int i = 0; i < (myNumVar + 1); i++) {
                if (myOkX[i]) {
                    j++;
                    myCoef[i] = coef[j - 1];
                    myStdErr[i] = Math.sqrt(myChiSq * xxInverse.getEntry(j - 1, j - 1) / (myCount - numX));
                    myTStat[i] = myCoef[i] / myStdErr[i];
                }
            }
        }

    }
    myIsComputed = true;
}

From source file:dr.math.Procrustes.java

public Procrustes(RealMatrix X, RealMatrix Xstar, boolean allowTranslation, boolean allowDilation) {
    rowDimension = X.getRowDimension();//  w ww  .  j  ava  2 s.c  o m
    columnDimension = X.getColumnDimension();

    if (Xstar.getRowDimension() != rowDimension) {
        throw new IllegalArgumentException("X and Xstar do not have the same number of rows");
    }
    if (Xstar.getColumnDimension() != columnDimension) {
        throw new IllegalArgumentException("X and Xstar do not have the same number of columns");
    }

    RealMatrix J = new Array2DRowRealMatrix(rowDimension, rowDimension);

    if (allowTranslation) {
        //           J <- diag(n) - 1/n * matrix(1, n, n)
        //           for n = 3, J = {{1, -2/3, -2/3}, {-2/3, 1, -2/3}, {-2/3, -2/3, 1}}

        for (int i = 0; i < rowDimension; i++) {
            J.setEntry(i, i, 1.0 - (1.0 / rowDimension));

            for (int j = i + 1; j < rowDimension; j++) {
                J.setEntry(i, j, -1.0 / rowDimension);
                J.setEntry(j, i, -1.0 / rowDimension);
            }
        }
    } else {
        //           J <- diag(n)

        for (int i = 0; i < rowDimension; i++) {
            J.setEntry(i, i, 1);
        }

    }

    //       C <- t(Xstar) %*% J %*% X

    RealMatrix C = Xstar.transpose().multiply(J.multiply(X));

    //       svd.out <- svd(C)
    //       R <- svd.out$v %*% t(svd.out$u)
    //      NB: Apache math does a different SVD from R.  TODO Should use Colt library
    SingularValueDecomposition SVD = new SingularValueDecompositionImpl(C);
    R = SVD.getV().multiply(SVD.getUT());

    //       s <- 1
    double s = 1.0; // scale = 1 unless dilation is being used

    if (allowDilation) {
        //           mat1 <- t(Xstar) %*% J %*% X %*% R
        RealMatrix mat1 = Xstar.transpose().multiply(J.multiply(X.multiply(R)));

        //           mat2 <- t(X) %*% J %*% X
        RealMatrix mat2 = X.transpose().multiply(J.multiply(X));

        //           s.numer <- 0
        //           s.denom <- 0
        double numer = 0.0;
        double denom = 0.0;

        //           for (i in 1:m) {
        //               s.numer <- s.numer + mat1[i, i]
        //               s.denom <- s.denom + mat2[i, i]
        //           }
        for (int i = 0; i < columnDimension; i++) {
            numer = numer + mat1.getEntry(i, i);
            denom = denom + mat2.getEntry(i, i);
        }
        //           s <- s.numer/s.denom
        s = numer / denom;
    }
    this.s = s;

    //       tt <- matrix(0, m, 1)
    RealMatrix tmpT = new Array2DRowRealMatrix(columnDimension, 1); // a translation vector of zero unless translation is being used

    if (allowTranslation) {
        //           tt <- 1/n * t(Xstar - s * X %*% R) %*% matrix(1, n, 1)
        RealMatrix tmp = new Array2DRowRealMatrix(rowDimension, 1);
        for (int i = 0; i < rowDimension; i++) {
            tmp.setEntry(i, 0, 1);
        }
        tmpT = Xstar.subtract(X.multiply(R).scalarMultiply(s)).transpose().scalarMultiply(1.0 / rowDimension)
                .multiply(tmp);
    }

    T = tmpT;
}

From source file:org.hippoecm.hst.demo.addonmodules.linearalgebra.MatrixOperatorImpl.java

public double[][] multiply(double[][] matrixData1, double[][] matrixData2) {
    RealMatrix m1 = new Array2DRowRealMatrix(matrixData1);
    RealMatrix m2 = new Array2DRowRealMatrix(matrixData2);
    RealMatrix result = m1.multiply(m2);
    return result.getData();
}

From source file:org.plista.kornakapi.core.recommender.FoldingFactorization.java

private double[][] computeUserFoldInMatrix(double[][] itemFeatures) {

    /* if there are no items, we cannot fold in anything */
    if (itemFeatures.length == 0) {
        return new double[0][0];
    }/* w  ww .  jav  a  2 s  .  co  m*/

    if (log.isInfoEnabled()) {
        log.info("Computing fold-in matrix from a {} x {} item features matrix", factorization.numItems(),
                factorization.numFeatures());
    }

    RealMatrix Y = new Array2DRowRealMatrix(itemFeatures);
    RealMatrix YTY = Y.transpose().multiply(Y);
    RealMatrix YTYInverse = new LUDecompositionImpl(YTY).getSolver().getInverse();

    return Y.multiply(YTYInverse).getData();
}

From source file:PowerMethod.power_method.java

public static power_object power_method(RealMatrix A, RealMatrix v, double epsilon, int N) {
    RealMatrix uInit = v;/* www .j a v  a2s .  c  o  m*/
    double k = 0;
    double prevK = 0;
    int num = 0;
    double accuracy;
    for (int i = N; i > 0; i--) {
        RealMatrix uN = A.multiply(uInit);
        k = uN.getEntry(0, 0);
        for (int j = 0; j < uN.getRowDimension(); j++) {
            uN.setEntry(j, 0, uN.getEntry(j, 0) / k);
        }
        uInit = uN;

        accuracy = Math.abs(k - prevK);
        if (accuracy <= epsilon) {
            break;
        }

        if (accuracy > epsilon && i == 1) {
            return null;
        }

        prevK = k;
        num++;
    }
    double eVal = k;
    RealMatrix eVec = new Array2DRowRealMatrix(uInit.getRowDimension(), uInit.getColumnDimension());

    eVec.setColumnMatrix(0, uInit.getColumnMatrix(0));
    power_object retVal = new power_object(eVal, eVec, num);
    return retVal;
}