Example usage for org.apache.commons.math3.linear RealMatrix getColumnDimension

List of usage examples for org.apache.commons.math3.linear RealMatrix getColumnDimension

Introduction

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

Prototype

int getColumnDimension();

Source Link

Document

Returns the number of columns in the matrix.

Usage

From source file:hivemall.utils.math.MatrixUtils.java

@Nonnull
public static double[] flatten(@Nonnull final RealMatrix[][] grid) {
    Preconditions.checkArgument(grid.length >= 1, "The number of rows must be greater than 1");
    Preconditions.checkArgument(grid[0].length >= 1, "The number of cols must be greater than 1");

    final int rows = grid.length;
    final int cols = grid[0].length;
    RealMatrix grid00 = grid[0][0];
    Preconditions.checkNotNull(grid00);/*  ww w  .  j  av a 2  s.  c o  m*/
    int cellRows = grid00.getRowDimension();
    int cellCols = grid00.getColumnDimension();

    final DoubleArrayList list = new DoubleArrayList(rows * cols * cellRows * cellCols);
    final RealMatrixPreservingVisitor visitor = new DefaultRealMatrixPreservingVisitor() {
        @Override
        public void visit(int row, int column, double value) {
            list.add(value);
        }
    };

    for (int row = 0; row < rows; row++) {
        for (int col = 0; col < cols; col++) {
            RealMatrix cell = grid[row][col];
            cell.walkInRowOrder(visitor);
        }
    }

    return list.toArray();
}

From source file:hivemall.utils.math.MatrixUtils.java

/**
 * QR decomposition for a tridiagonal matrix T.
 *
 * @see https://gist.github.com/lightcatcher/8118181
 * @see http://www.ericmart.in/blog/optimizing_julia_tridiag_qr
 * @param T target tridiagonal matrix/*from   w ww  .jav  a 2  s  .  co  m*/
 * @param R output matrix for R which is the same shape as T
 * @param Qt output matrix for Q.T which is the same shape an T
 */
public static void tridiagonalQR(@Nonnull final RealMatrix T, @Nonnull final RealMatrix R,
        @Nonnull final RealMatrix Qt) {
    int n = T.getRowDimension();
    Preconditions.checkArgument(n == R.getRowDimension() && n == R.getColumnDimension(),
            "T and R must be the same shape");
    Preconditions.checkArgument(n == Qt.getRowDimension() && n == Qt.getColumnDimension(),
            "T and Qt must be the same shape");

    // initial R = T
    R.setSubMatrix(T.getData(), 0, 0);

    // initial Qt = identity
    Qt.setSubMatrix(eye(n), 0, 0);

    for (int i = 0; i < n - 1; i++) {
        // Householder projection for a vector x
        // https://en.wikipedia.org/wiki/Householder_transformation
        RealVector x = T.getSubMatrix(i, i + 1, i, i).getColumnVector(0);
        x = unitL2norm(x);

        RealMatrix subR = R.getSubMatrix(i, i + 1, 0, n - 1);
        R.setSubMatrix(subR.subtract(x.outerProduct(subR.preMultiply(x)).scalarMultiply(2)).getData(), i, 0);

        RealMatrix subQt = Qt.getSubMatrix(i, i + 1, 0, n - 1);
        Qt.setSubMatrix(subQt.subtract(x.outerProduct(subQt.preMultiply(x)).scalarMultiply(2)).getData(), i, 0);
    }
}

From source file:edu.cudenver.bios.matrix.MatrixUtils.java

/**
 * This method will return vech(matrix).
 * matrix must be symmetric in order to perform vech operation.
 * @param RealMatrix matrix//from  ww  w .j ava2  s . c  o  m
 * @return vech(matrix)
 */
public static RealMatrix getVechMatrix(RealMatrix matrix) throws IllegalArgumentException {
    if (matrix == null || !isSymmetric(matrix)) {
        throw new IllegalArgumentException("Matrix must be non-null and " + "symmetrical.");
    }
    int newRow = 0;
    int numRows = matrix.getRowDimension();
    RealMatrix vech = new Array2DRowRealMatrix(numRows * (numRows + 1) / 2, 1);
    for (int c = 0; c < matrix.getColumnDimension(); c++) {
        for (int r = c; r < matrix.getRowDimension(); r++, newRow++) {
            vech.setEntry(newRow, 0, matrix.getEntry(r, c));
        }
    }
    return vech;
}

From source file:hivemall.utils.math.MatrixUtils.java

/**
 * Find the first singular vector/value of a matrix A based on the Power method.
 *
 * @see http/*from w  w w .  j a  v  a 2  s  .c  o  m*/
 *      ://www.cs.yale.edu/homes/el327/datamining2013aFiles/07_singular_value_decomposition.pdf
 * @param A target matrix
 * @param x0 initial vector
 * @param nIter number of iterations for the Power method
 * @param u 1st left singular vector
 * @param v 1st right singular vector
 * @return 1st singular value
 */
public static double power1(@Nonnull final RealMatrix A, @Nonnull final double[] x0, final int nIter,
        @Nonnull final double[] u, @Nonnull final double[] v) {
    Preconditions.checkArgument(A.getColumnDimension() == x0.length,
            "Column size of A and length of x should be same");
    Preconditions.checkArgument(A.getRowDimension() == u.length,
            "Row size of A and length of u should be same");
    Preconditions.checkArgument(x0.length == v.length, "Length of x and u should be same");
    Preconditions.checkArgument(nIter >= 1, "Invalid number of iterations: " + nIter);

    RealMatrix AtA = A.transpose().multiply(A);

    RealVector x = new ArrayRealVector(x0);
    for (int i = 0; i < nIter; i++) {
        x = AtA.operate(x);
    }

    double xNorm = x.getNorm();
    for (int i = 0, n = v.length; i < n; i++) {
        v[i] = x.getEntry(i) / xNorm;
    }

    RealVector Av = new ArrayRealVector(A.operate(v));
    double s = Av.getNorm();

    for (int i = 0, n = u.length; i < n; i++) {
        u[i] = Av.getEntry(i) / s;
    }

    return s;
}

From source file:edu.cudenver.bios.matrix.MatrixUtils.java

/**
 * Horizontally append two matrices//from w  w w .j  av a2s  .  c  o  m
 * @param matrix
 * @param column
 * @return the combined matrix
 * @throws IllegalArgumentException
 */
public static RealMatrix getHorizontalAppend(RealMatrix m1, RealMatrix m2) throws IllegalArgumentException {
    if (m1 == null || m2 == null)
        throw new IllegalArgumentException("Missing required argument");
    if (m1.getRowDimension() != m2.getRowDimension())
        throw new IllegalArgumentException("Row dimensions must be equal");

    RealMatrix newMatrix = new Array2DRowRealMatrix(m1.getRowDimension(),
            m1.getColumnDimension() + m2.getColumnDimension());
    newMatrix.setSubMatrix(m1.getData(), 0, 0);
    newMatrix.setSubMatrix(m2.getData(), 0, m1.getColumnDimension());

    return newMatrix;
}

From source file:hivemall.utils.math.MatrixUtils.java

@Nonnull
public static RealMatrix combinedMatrices(@Nonnull final RealMatrix[] grid) {
    Preconditions.checkArgument(grid.length >= 1, "The number of rows must be greater than 0: " + grid.length);

    final int rows = grid.length;
    final int rowDims = grid[0].getRowDimension();
    final int colDims = grid[0].getColumnDimension();

    final RealMatrix combined = new BlockRealMatrix(rows * rowDims, colDims);
    for (int row = 0; row < grid.length; row++) {
        RealMatrix cell = grid[row];
        Preconditions.checkArgument(cell.getRowDimension() == rowDims, "Mismatch in row dimensions at row ",
                row);/*from  ww w. ja  v a 2 s.c om*/
        Preconditions.checkArgument(cell.getColumnDimension() == colDims, "Mismatch in col dimensions at row ",
                row);
        combined.setSubMatrix(cell.getData(), row * rowDims, 0);
    }
    return combined;
}

From source file:edu.cudenver.bios.matrix.MatrixUtils.java

/**
 * Calculate the horizontal direct product of two matrices
 *
 * @param matrix1 first matrix/*  www.  ja v a2s.c  o m*/
 * @param matrix2 second matrix
 * @return horizontal direct product of matrix 1 and matrix 2
 */
public static RealMatrix getHorizontalDirectProduct(RealMatrix matrix1, RealMatrix matrix2)
        throws IllegalArgumentException {
    if (matrix1 == null || matrix2 == null)
        throw new IllegalArgumentException("null input matrix");
    if (matrix1.getRowDimension() != matrix2.getRowDimension())
        throw new IllegalArgumentException("input matrices must have equal row dimension");

    int mRows = matrix1.getRowDimension();
    int m1Cols = matrix1.getColumnDimension();
    int m2Cols = matrix2.getColumnDimension();

    double[][] productData = new double[mRows][m1Cols * m2Cols];
    RealMatrix productMatrix = new Array2DRowRealMatrix(productData);
    for (int col = 0; col < m1Cols; col++) {
        for (int row = 0; row < mRows; row++) {
            RealMatrix m2Row = matrix2.getRowMatrix(row);
            productMatrix.setSubMatrix((m2Row.scalarMultiply(matrix1.getEntry(row, col))).getData(), row,
                    col * m2Cols);
        }
    }
    return productMatrix;
}

From source file:edu.cudenver.bios.matrix.MatrixUtils.java

/**
 * This method will return the element-wise product of matrixA
 * and matrixB.// w  w  w  .jav  a2s. co m
 * In order to perform element-wise multiplication, the incoming
 * matrices must have the same dimensions.
 * @param matrixA
 * @param matrixB
 * @return RealMatrix which is the element-wise product of A and B.
 */
public static RealMatrix getElementWiseProduct(RealMatrix matrixA, RealMatrix matrixB)
        throws IllegalArgumentException {
    if (matrixA == null || matrixB == null || !areDimensionsEqual(matrixA, matrixB)) {
        throw new IllegalArgumentException("Both matrices must be non-null "
                + "and matrix dimensions must be equal" + " for element-wise multiplication.");
    }

    int numRows = matrixA.getRowDimension();
    int numCols = matrixA.getColumnDimension();
    RealMatrix product = new Array2DRowRealMatrix(numRows, numCols);
    double aVal, bVal;

    //loop through each row
    for (int r = 0; r < numRows; r++) {
        //multiply each element of A by same element of B
        for (int c = 0; c < numCols; c++) {
            aVal = matrixA.getEntry(r, c);
            bVal = matrixB.getEntry(r, c);
            product.setEntry(r, c, aVal * bVal);
        }
    }
    return product;
}

From source file:hivemall.utils.math.MatrixUtils.java

/**
 * Find eigenvalues and eigenvectors of given tridiagonal matrix T.
 *
 * @see http://web.csulb.edu/~tgao/math423/s94.pdf
 * @see http://stats.stackexchange.com/questions/20643/finding-matrix-eigenvectors-using-qr-
 *      decomposition//w  w w .j av a  2 s .co  m
 * @param T target tridiagonal matrix
 * @param nIter number of iterations for the QR method
 * @param eigvals eigenvalues are stored here
 * @param eigvecs eigenvectors are stored here
 */
public static void tridiagonalEigen(@Nonnull final RealMatrix T, @Nonnull final int nIter,
        @Nonnull final double[] eigvals, @Nonnull final RealMatrix eigvecs) {
    Preconditions.checkArgument(Arrays.deepEquals(T.getData(), T.transpose().getData()),
            "Target matrix T must be a symmetric (tridiagonal) matrix");
    Preconditions.checkArgument(eigvecs.getRowDimension() == eigvecs.getColumnDimension(),
            "eigvecs must be a square matrix");
    Preconditions.checkArgument(T.getRowDimension() == eigvecs.getRowDimension(),
            "T and eigvecs must be the same shape");
    Preconditions.checkArgument(eigvals.length == eigvecs.getRowDimension(),
            "Number of eigenvalues and eigenvectors must be same");

    int nEig = eigvals.length;

    // initialize eigvecs as an identity matrix
    eigvecs.setSubMatrix(eye(nEig), 0, 0);

    RealMatrix T_ = T.copy();

    for (int i = 0; i < nIter; i++) {
        // QR decomposition for the tridiagonal matrix T
        RealMatrix R = new Array2DRowRealMatrix(nEig, nEig);
        RealMatrix Qt = new Array2DRowRealMatrix(nEig, nEig);
        tridiagonalQR(T_, R, Qt);

        RealMatrix Q = Qt.transpose();
        T_ = R.multiply(Q);
        eigvecs.setSubMatrix(eigvecs.multiply(Q).getData(), 0, 0);
    }

    // diagonal elements correspond to the eigenvalues
    for (int i = 0; i < nEig; i++) {
        eigvals[i] = T_.getEntry(i, i);
    }
}

From source file:hivemall.utils.math.MatrixUtils.java

/**
 * Lanczos tridiagonalization for a symmetric matrix C to make s * s tridiagonal matrix T.
 *
 * @see http://www.cas.mcmaster.ca/~qiao/publications/spie05.pdf
 * @param C target symmetric matrix/* w  w  w .j av  a2s .c  om*/
 * @param a initial vector
 * @param T result is stored here
 */
public static void lanczosTridiagonalization(@Nonnull final RealMatrix C, @Nonnull final double[] a,
        @Nonnull final RealMatrix T) {
    Preconditions.checkArgument(Arrays.deepEquals(C.getData(), C.transpose().getData()),
            "Target matrix C must be a symmetric matrix");
    Preconditions.checkArgument(C.getColumnDimension() == a.length,
            "Column size of A and length of a should be same");
    Preconditions.checkArgument(T.getRowDimension() == T.getColumnDimension(), "T must be a square matrix");

    int s = T.getRowDimension();

    // initialize T with zeros
    T.setSubMatrix(new double[s][s], 0, 0);

    RealVector a0 = new ArrayRealVector(a.length);
    RealVector r = new ArrayRealVector(a);

    double beta0 = 1.d;

    for (int i = 0; i < s; i++) {
        RealVector a1 = r.mapDivide(beta0);
        RealVector Ca1 = C.operate(a1);

        double alpha1 = a1.dotProduct(Ca1);

        r = Ca1.add(a1.mapMultiply(-1.d * alpha1)).add(a0.mapMultiply(-1.d * beta0));

        double beta1 = r.getNorm();

        T.setEntry(i, i, alpha1);
        if (i - 1 >= 0) {
            T.setEntry(i, i - 1, beta0);
        }
        if (i + 1 < s) {
            T.setEntry(i, i + 1, beta1);
        }

        a0 = a1.copy();
        beta0 = beta1;
    }
}