Class Matrix

java.lang.Object
jline.util.matrix.Matrix
All Implemented Interfaces:
Serializable

public final class Matrix extends Object implements Serializable
A sparse matrix data structure supporting linear algebra functions similar to those available in MATLAB. TABLE OF CONTENTS: 1. CONSTRUCTORS AND INITIALIZATION 2. CORE ELEMENT ACCESS AND MODIFICATION 3. BASIC ARITHMETIC OPERATIONS 4. ELEMENT-WISE OPERATIONS 5. MATRIX TRANSFORMATIONS 6. LINEAR ALGEBRA OPERATIONS 7. MATRIX SLICING AND EXTRACTION 8. MATRIX CONCATENATION AND ASSEMBLY 9. STATISTICAL OPERATIONS 10. MATRIX PROPERTIES AND COMPARISONS 11. FINDING AND FILTERING 12. MATRIX MANIPULATION 13. SPECIAL MATRIX OPERATIONS 14. I/O OPERATIONS 15. FACTORY METHODS 16. UTILITY METHODS
See Also:
  • Constructor Summary

    Constructors
    Constructor
    Description
    Matrix(double[] array)
    Creates a column vector from a double array.
    Matrix(double[][] arrays)
    Creates a matrix from a 2D double array.
    Matrix(int[] array)
    Creates a column vector from an integer array.
    Matrix(int numRows, int numCols)
    Creates a sparse matrix with the specified dimensions.
    Matrix(int numRows, int numCols, int arrayLength)
    Creates a sparse matrix with the specified dimensions and capacity.
    Matrix(Double[][] arrays)
    Creates a matrix from a Kotlin Array type.
    Matrix(String matrixString)
    Parse matrix from string in MATLAB or Python formats MATLAB format assumes commas between row elements and semicolon between rows
     
    Matrix(List<Double> array)
     
    Matrix(Matrix matrix)
    Creates a copy of the specified matrix.
    Matrix(org.ejml.data.DMatrix matrix)
    Creates a matrix from an EJML DMatrix (sparse).
    Matrix(org.ejml.data.DMatrixRMaj matrix)
    Creates a matrix from an EJML DMatrixRMaj (dense).
    Matrix(org.ejml.simple.SimpleMatrix matrix)
     
  • Method Summary

    Modifier and Type
    Method
    Description
    void
     
    add(double alpha)
    Adds a scalar multiple of the all-ones matrix to this matrix: this + alpha * 1.
    add(double alpha, Matrix matrix)
    Adds alpha * matrix to this matrix.
    add(Matrix matrix)
    Adds another matrix to this matrix: this + matrix.
    void
    addEq(double alpha)
    Adds a scalar value to each element of the matrix in-place.
    void
    addEq(double alpha, Matrix matrix)
    Adds alpha * matrix to this matrix in-place: this += alpha * matrix.
    void
    addEq(Matrix matrix)
    Adds another matrix to this matrix in-place: this += matrix.
    static Matrix
    allbut(Matrix y, int k)
    Returns all elements in a matrix except the first ones
    boolean
    Checks whether all elements in the matrix are equal to 1.
    boolean
    any()
     
    void
    apply(double source, double target, String op)
    Applies a conditional element-wise transformation to the matrix.
    static Matrix
    broadcastColPlusRow(Matrix colVector, Matrix rowVector)
    Computes the element-wise sum of a column vector and a row vector, producing a matrix where each entry (i, j) is the sum of colVector[i] and rowVector[j].
    static Matrix
    cartesian(Matrix matrixA, Matrix matrixB)
    Cartesian product of two matrices.
    Returns a new matrix where each element is the ceiling of the corresponding element in this matrix.
    Applies the ceiling operation in-place to each element of this matrix.
    static Matrix
    cell2mat(Map<Integer,Matrix> cellArray)
    Concatenates a collection of matrices stored in a map into a single row vector.
    static Matrix
    cellsum(Map<Integer,Matrix> cellArray)
    Computes the element-wise sum of all matrices stored in a map.
    void
    Negates all values in the matrix, in-place.
    void
    colIncrease(int col, double a)
     
    Returns the matrix in column-major order.
    Equivalent to the colon operator in MATLAB (:).
    static double[]
    Converts a column matrix (of size m x 1) to a dense double array of length m.
    static boolean
    Compares two matrices element-wise using a specified comparison operator.
    boolean
    Compares this matrix to another matrix for approximate equality.
    Performs element-wise addition with shape broadcasting where applicable.
    Concatenates this matrix with another matrix horizontally.
    static Matrix
    concatColumns(Matrix left, Matrix right, Matrix out)
    Concatenates two matrices horizontally (column-wise).
    static Matrix
    concatRows(Matrix top, Matrix bottom, Matrix out)
    Concatenates two matrices vertically (row-wise).
    Returns a deep copy of this matrix.
    int
    count(double val)
    Counts how many elements in the matrix are equal to a specified value.
    countEachRow(double val)
    Counts the number of occurrences of a value in each row of the matrix.
    Creates a block diagonal matrix by placing the current matrix in the top-left and another matrix (if provided) in the bottom-right.
    static Matrix
    Creates a new empty matrix with the same shape and internal structure as the given matrix.
    Computes the cumulative sum of the matrix down each column.
    Computes the cumulative sum of the matrix across each row.
    static Matrix
    decorate(Matrix inspace1, Matrix inspace2)
     
    double
    det()
    Computes the determinant of the matrix.
    static Matrix
    diag(double... values)
    Creates a square diagonal matrix from the given values.
    static Matrix
    diagMatrix(double[] values)
    Creates a square diagonal matrix from a given array of values.
    static Matrix
    Creates a square diagonal matrix from the elements of a column or row vector matrix.
    static Matrix
    diagMatrix(Matrix A, double[] values, int offset, int length)
    Creates or fills a square diagonal matrix with the specified values.
    div(Matrix den)
    Performs element-wise division between this matrix and the provided matrix.
    void
    Performs in-place element-wise division between this matrix and the provided matrix.
    void
    divide(double scalar, Matrix outputB, boolean flag)
    Divides this matrix by a scalar and stores the result in the output matrix.
    void
    divideEq(double scalar)
    Performs in-place division of this matrix by a scalar.
    void
    divideRows(double[] diag, int offset)
    Divides each row of this matrix by the corresponding diagonal element (with an offset).
    static Matrix
    Solves the discrete Sylvester equation A * X * B - X + C = 0.
    List<org.apache.commons.math3.complex.Complex>
    eig()
    Computes the eigenvalues of this square matrix, including complex eigenvalues.
    Computes the eigenvalues of this square matrix.
    Computes the eigenvalues and eigenvectors of this square matrix.
    Performs element-wise division of this matrix by another matrix.
    Performs element-wise division with another matrix.
    elementIncrease(double val)
    Increases each element of the matrix by a constant value.
    double
    Returns the maximum value among all elements in the matrix.
    double
    Returns the maximum absolute value among all elements in the matrix.
    double
    Returns the minimum value among all elements in the matrix.
    static double
    Returns the smallest non-zero positive element in the given matrix.
    double
    Computes the product of the elements of a row or column vector.
    Performs in-place element-wise multiplication with another matrix.
    Performs element-wise multiplication with another matrix, storing the result in the given output matrix.
    Performs element-wise multiplication between this matrix and a row vector.
    elementPow(double a)
    Raises each non-zero element of the matrix to the specified power.
    elementPower(double t)
    Raises each element of the matrix to the given power.
    double
    Computes the sum of all elements in the matrix.
    boolean
    Checks for matrix equality.
    exp()
    Applies the exponential function to each element of the matrix.
    void
    expandMatrix(int rows, int cols, int nz_length)
    Expands the matrix dimensions to the specified size while preserving data.
    void
    Expands the matrix to be square, padding with zeros as needed.
    Computes the matrix exponential.
    Computes the matrix exponential using Higham's scaling and squaring method.
    static Matrix
    extract(Matrix src, int srcX0, int srcX1, int srcY0, int srcY1)
    Extracts a rectangular submatrix from the given source matrix.
    static void
    extract(Matrix src, int srcX0, int srcX1, int srcY0, int srcY1, Matrix dst, int dstY0, int dstX0)
    Extracts a rectangular submatrix from a source matrix and stores it in a destination matrix.
    extractCols(int col0, int col1)
    Extracts a range of columns from this matrix (instance method).
    static Matrix
    extractColumn(Matrix A, int column, Matrix out)
    Extracts a single column from the given matrix.
    static Matrix
    extractColumns(Matrix A, int col0, int col1)
    Extracts a range of columns from the matrix [col0:col1).
    static Matrix
    extractColumns(Matrix A, int col0, int col1, Matrix out)
    Extracts a range of columns from the matrix [col0:col1) into a destination matrix.
    static void
    extractDiag(Matrix A, Matrix outputB)
    Extracts the diagonal elements of a matrix and stores them in a destination matrix.
    extractRows(int row0, int row1)
    Extracts rows from this matrix (instance method).
    static Matrix
    extractRows(Matrix A, int row0, int row1)
    Extracts a range of rows from the matrix [row0:row1).
    static Matrix
    extractRows(Matrix A, int row0, int row1, Matrix out)
    Extracts a range of rows from the matrix [row0:row1) into a destination matrix.
    static Matrix
    eye(int length)
    Creates an identity matrix of given size.
    Computes the factorial of each element in the matrix.
    Computes the natural logarithm of the factorial for each element.
    static Matrix
    Computes the natural logarithm of the factorial (log(x!)) for each element in the input matrix.
    fill(double val)
    Fills all entries in the matrix with the given value.
    Returns the linear indices of all non-zero elements in the matrix.
    static List<Integer>
    findIndexWithZeroSum(Matrix matrix, boolean isRow)
    Finds the indices of all rows or columns in a matrix that have a sum of zero.
    Returns the linear indices of all elements that are non-negative (≥ 0).
    Finds all row indices in a given column where the value is non-zero.
    findNumber(double number)
    Finds all linear indices where the matrix has a specific value.
    static List<Integer>
    findRows(Matrix matrix, Matrix row)
    Finds the indices of all rows in a matrix that exactly match a given row vector.
    Finds all linear indices where the matrix value is zero.
    static double
    Computes the 1-norm (maximum absolute column sum) of the matrix.
    fromArray2D(double[][] matrix)
    Populates the matrix from a 2D double array.
    fromArray2D(int[][] matrix)
    Populates the matrix from a 2D integer array.
    static Matrix
    Constructs a Matrix from a list of rows, where each inner list is a row.
    double
    get(int idx)
    Returns the value at the specified index.
    double
    get(int i, int j)
    Returns the value at the specified row and column.
    int[]
    Returns internal column index array from the sparse matrix structure.
    static int
    Computes the total number of elements across all matrices in a map, summing numRows * numCols for each matrix.
    int
    getColMax(int col)
    Returns the row index of the maximum value in the specified column.
    getColumn(int j)
    Returns a column of the matrix as a new single-column matrix.
    Returns a lightweight view into the specified column without copying data.
    org.ejml.data.DMatrix
     
    int[]
    Returns an array of unique column indices containing non-zero elements.
    int
    Returns the number of non-zero values in the matrix.
    int[]
    Returns array of row indices of non-zero entries.
    int
    Returns the number of non-zero elements in this matrix.
    double[]
    Returns array of non-zero values in the matrix.
    int
    Returns the number of columns in this matrix.
    int
    Returns total number of elements in the matrix.
    int
     
    int
    Returns the number of rows in this matrix.
    getRow(int i)
    Returns the specified row as a single-row matrix.
    int
    getRowMax(int row)
    Returns column index of maximum element in a specified row.
    getRowsFrom(int row)
    Returns a new matrix consisting of rows from the given start index to the end.
    getRowView(int i)
    Returns a lightweight view into the specified row without copying data.
    getSlice(boolean[] rowFlags, boolean[] colFlags)
    Extracts a submatrix from rows/columns marked as true in input flags.
    getSlice(int r0, int r1, int c0, int c1)
    Extracts a submatrix based on row/column bounds.
    static Matrix
    getSubMatrix(Matrix sourceMatrix, int x0, int x1, int y0, int y1)
    Extracts a submatrix from the source matrix using zero-based index ranges.
    getSubMatrix(Matrix rows, Matrix cols)
    Returns a matrix consisting of rows and columns selected by two index matrices.
    void
    growMaxColumns(int newmax, boolean preserve)
    Increases the internal column capacity of the matrix.
    void
    growMaxLength(int newmax, boolean preserve)
    Increases the internal non-zero element capacity of the matrix.
    Performs the Hadamard (element-wise) product of two matrices.
    boolean
     
    boolean
     
    int
    Generates a hash code for the matrix based on its values.
    boolean
     
    boolean
     
    boolean
     
    double
    Computes the infinity norm of this matrix.
    static double
    Computes the infinity norm (maximum absolute row sum) of the matrix.
    void
    insertSubMatrix(int start_row, int start_col, int end_row, int end_col, Matrix matrix_to_be_inserted)
    Inserts a sub-matrix into the current matrix at the specified location.
    static List<Double>
    intersect(Matrix matrixA, Matrix matrixB)
    Computes the intersection of scalar values present in two matrices.
    inv()
    Computes the inverse of the matrix.
    static Matrix
    Computes the inverse of the given matrix.
    boolean
    isAssigned(int row, int col)
    Checks whether a specific element is assigned in the sparse matrix.
    boolean
    Determines whether the matrix is a diagonal matrix.
    boolean
    Checks if the matrix is empty (has zero rows or columns).
    boolean
    Checks if two matrices are exactly equal.
    boolean
    isEqualToTol(Matrix m, double tol)
    Checks if two matrices are equal within a specified tolerance.
    boolean
    Checks whether all matrix elements are finite.
    boolean
    Checks if all values in the matrix are integers.
    void
    Keeps only the specified columns in the matrix.
    void
    Keeps only the specified rows in the matrix.
    Computes the Kronecker product of this matrix and another matrix.
    krons(Matrix other)
    Computes the Kronecker sum of two matrices: A ⊕ B = A \otimes I + I \otimes B, where \otimes is the Kronecker product and I is the identity matrix of matching size.
    Solves the equation AX = B for X, where A is this matrix and B is the right-hand side.
    int
    Returns the length of the matrix, defined as max(rows, cols).
    log()
    Applies the natural logarithm element-wise.
    static double
    logSum(Matrix matrix)
    Computes the sum of the natural logarithms of all elements in the matrix.
    static double
    Computes log(sum_i exp(x_i)) in a numerically stable way (log-sum-exp trick).
    static Matrix
    lyap(Matrix A, Matrix B, Matrix C, Matrix D)
    Computes the solution to the continuous-time Lyapunov equation AX + XAᵀ + Q = 0.
    static int
    matchrow(Matrix matrix, Matrix row)
    Returns the index of the row in the matrix that exactly matches the given row vector.
    static Matrix
    matrixAddVector(Matrix matrix, Matrix vector)
    Adds a vector to each row or column of the matrix, depending on the vector's orientation.
    static double
    Computes the maximum relative absolute difference between corresponding elements of two matrices: max(abs((a - b) / b)).
    Computes the mean of each column.
    Computes the mean of each row.
    void
    Multiplies all elements in the matrix by -1 in-place.
    Performs matrix multiplication: this * B
    mult(Matrix B, Matrix out)
    Performs matrix multiplication: this * B
    double
    Efficiently multiplies this row vector with a column view.
    void
    Replaces this matrix with the result of this * B.
    double
    Efficiently multiplies a row view with this column vector.
    neg()
    Returns the negation of this matrix (all elements multiplied by -1).
    static Matrix
    Negates all elements in the matrix and returns the result.
    double
    Computes the Euclidean norm of a matrix
    double
    Computes the 1-norm of the matrix (maximum absolute column sum).
    double
    Computes the Frobenius norm of a matrix (alias for norm()).
    static Matrix
    Computes the matrix 1 - A, where diagonal entries become 1 - A(i, i) and off-diagonal entries become -A(i, j).
    static Matrix
    Decreases a single element of an integer vector by one.
    static Matrix
    Decreases multiple elements of an integer vector by one.
    void
    Fills the matrix with ones.
    static Matrix
    ones(int rows, int cols)
    Creates a matrix of the given shape filled with ones.
    Computes the Moore-Penrose pseudo-inverse of the matrix using SVD.
    static Matrix
    pow(Matrix a, int b)
    Computes the matrix power A^b for a non-negative integer exponent b.
    double
    powerSumCols(int col, double alpha)
    Computes the sum of powers of absolute values in a column: ∑ |A_{ji}|^alpha
    double
    powerSumRows(int row, double alpha)
    Computes the sum of powers of absolute values in a row: ∑ |A_{ij}|^alpha
    void
    Pretty prints the matrix with automatic formatting and alignment.
    void
    Pretty prints the matrix assuming integer values.
    void
    Prints the matrix with appropriate formatting, either as floats or integers.
    void
    Prints only non-zero values and their positions in the matrix.
    qr()
    Performs QR decomposition on the matrix.
    void
    randMatrix(int length)
    Fills the matrix with random values between 0 and 1.
    int
    Computes the rank of the matrix.
    static Matrix
    readFromFile(String fileName)
    Reads a CSV-formatted matrix from a file.
    Computes the element-wise reciprocal (1/x) of the matrix.
    void
    remove(int row, int col)
    Removes a specific element from the matrix at the given row and column.
    void
    Removes the specified columns from the matrix.
    void
    Replaces all infinite values (positive or negative) in the matrix with 0.
    void
    Removes all infinite values (positive or negative) from the sparse matrix structure.
    void
    Removes all NaN values from the matrix structure.
    void
    Removes all negative values from the matrix structure.
    static double[][][]
    removeRows(double[][][] array, Matrix rowsToRemove)
     
    void
    Removes the specified rows from the matrix.
    static String
     
    void
    removeZeros(double val)
    Removes values from the matrix that are equal to the specified value.
    void
    replace(double delete, double replacement)
    Replaces all occurrences of a specific value with a new value in the matrix.
    repmat(int rows, int cols)
    Repeats the matrix to match the specified row and column replication.
    void
    reshape(int numRows, int numCols)
    Reshapes the matrix to the specified number of rows and columns.
    void
    reshape(int numRows, int numCols, int arrayLength)
    Reshapes the matrix with new dimensions and internal storage length.
    Reverses the elements of a vector (row or column) matrix.
    Reverses the order of rows in the matrix.
    Performs right matrix division A / B = A * inv(B)
    static Matrix
    Robust linear solve for A·X = B that handles singular matrices.
    void
    rowIncrease(int row, double a)
    Increases all elements in the specified row by a scalar value.
     
    scale(double scalar)
    Scales the matrix by the given scalar value.
    void
    scaleEq(double scalar)
    Scales this matrix in-place by the given scalar value.
    void
    scaleEq(double scalar, Matrix output)
    Scales this matrix by the given scalar value and stores the result in the provided output matrix.
    static Matrix
    scaleMult(Matrix a, double n)
    Multiplies all elements of a matrix by a scalar.
    Computes the Schur decomposition with the default method and iteration count.
    schur(String method, Integer iter)
    Computes the Schur decomposition of the matrix.
    Computes the complex Schur decomposition of this matrix, equivalent to MATLAB's schur(A,'complex').
    void
    set(int idx, double val)
    Sets the element at absolute index position to the given value.
    void
    set(int row, int col, double val)
    Sets the element at specified row and column.
    void
    set(int row, int col, int val)
    Sets the element at specified row and column using an integer value.
    setColumn(int j, Matrix col)
    Sets the specified column to the values in the given vector.
    setColumns(int j0, int j1, Matrix cols)
    Sets multiple columns starting from column index j0 to j1 (exclusive) using values from another matrix.
    void
    setData(org.ejml.data.DMatrix newData)
     
    void
    setNaNTo(double val)
    Replaces all NaN entries in the matrix with the specified value.
    void
    Replaces all NaN entries in the matrix with zero.
    setRow(int j, Matrix row)
    Sets the specified row to the values in the given vector.
    setRows(int i0, int i1, Matrix rows)
    Sets multiple rows starting from row index i0 to i1 (exclusive) using values from another matrix.
    setSlice(int rowStart, int rowEnd, int colStart, int colEnd, Matrix newSlice)
    Returns a new matrix representing the updated slice after assigning values from newSlice.
    void
    setSliceEq(int rowStart, int rowEnd, int colStart, int colEnd, Matrix newSlice)
    Sets the values of a submatrix (in-place) using the specified newSlice matrix.
    void
    Copies the data from another matrix into this matrix.
    void
    Sets all elements of the matrix to NaN.
    void
    shrinkNumCols(int newmax)
     
    void
    shrinkNumRows(int newmax)
     
    static Matrix
    singleton(double value)
    Creates a 1×1 matrix containing a single scalar value.
    static boolean
    Solves the sparse linear system Ax = b.
    static boolean
    Solves the linear system A*x = b directly using LU decomposition without singularity checks.
    static boolean
    Solves the linear system Ax = b for x, handling singular matrices gracefully.
    Returns a new matrix with the non-zero values sorted in ascending order.
    Sorts the current matrix's non-zero values in place.
    Computes the spectral decomposition of a matrix A using its eigendecomposition.
    Computes the element-wise square root of the matrix.
    Computes the matrix multiplied by itself.
    sub(double x)
    Subtract a scalar from all elements.
    sub(double alpha, Matrix matrix)
    Subtracts alpha-scaled version of the provided matrix.
    sub(Matrix matrix)
    Subtracts another matrix.
    void
    subEq(double x)
    Subtracts a scalar from the current matrix in place.
    void
    subEq(double alpha, Matrix matrix)
    Subtracts a scaled matrix from the current matrix in place.
    void
    subEq(Matrix matrix)
    Subtracts a matrix from the current matrix in place.
    double
    sumAbsCols(int col)
    Sums the absolute values of the given column.
    double
    sumAbsRows(int row)
    Sums the absolute values of the given row.
    Sums the values in each column and returns the results as a row vector.
    double
    sumCols(int col)
    Sums the elements in the specified column.
    sumCols(int startRow, int endRow)
    Computes the sum of a subset of rows for each column.
    static double
    Computes the sum of the cumulative product along a row vector.
    Computes the sum of each row and returns the result as a column vector.
    double
    sumRows(int row)
    Computes the sum of the values in a specific row.
    sumRows(int startCol, int endCol)
    Computes the sum over a subrange of columns for each row.
    double
    sumSubMatrix(boolean[] rowIndexes, boolean[] colIndexes)
    Computes the sum of a submatrix defined by boolean selection flags.
    double
    sumSubMatrix(int[] rowIndexes, int[] colIndexes)
    Computes the sum of a submatrix defined by specific row and column indices.
    double
    sumSubMatrix(int startRow, int endRow, int startCol, int endCol)
    Computes the sum of the values in a rectangular submatrix.
    svd()
    Computes the Singular Value Decomposition (SVD) of this matrix.
    static Matrix
    sylv(Matrix A, Matrix B, Matrix C)
    Solves the Sylvester equation A·X + X·B = -C using a Schur decomposition-based method.
    double[]
    Converts the matrix to a flat 1D array in row-major order.
    double[][]
    Converts the matrix to a 2D array representation.
    org.ejml.data.DMatrixSparseCSC
    Converts this matrix to a copy of its underlying DMatrixSparseCSC structure.
    org.ejml.data.DMatrixSparseCSC
    Converts a specified matrix to a copy of its underlying DMatrixSparseCSC structure.
    Converts this matrix to a single Double value.
    Converts the matrix to a nested list of Double values.
    int[]
    Converts the matrix to a 1D array of int, flattening in row-major order.
    Converts the matrix into a 1D List of Double values in row-major order.
    Returns a formatted string representation of the matrix.
    Computes the transpose of the current matrix.
    static Matrix
    tril(Matrix matrix)
    Returns the lower triangular part of a matrix (zeroing elements above the main diagonal).
    static Matrix
    tril(Matrix matrix, int k)
    Returns the elements on and below the kth diagonal of matrix A.
    static Matrix
    Computes the union of two matrices A and B.
    uniqueInCol(int colIdx)
    Finds unique integer values in the specified column of the matrix.
    uniqueInRow(int rowIdx)
    Finds unique integer values in the specified row of the matrix.
    Finds unique positive values (strictly greater than 0) in the specified column.
    Finds unique positive values (strictly greater than 0) in the specified row.
    uniqueNonZerosInCol(int colIdx)
    Finds unique non-zero values in the specified column.
    uniqueNonZerosInRow(int rowIdx)
    Finds unique non-zero values in the specified row.
    Finds the indices of unique rows in a matrix without returning a matrix of the unique rows themselves.
    Identifies unique rows in a matrix starting from a specified column index.
    Finds all unique rows in a matrix and returns the unique sorted rows, along with mapping indices to/from the original matrix.
    void
    unsafeSet(int row, int col, double val)
    Sets a value in the matrix without bounds checking.
    double
    Returns the value at position (0, 0).
    static Set<Set<Integer>>
    weaklyConnect(Matrix param, Set<Integer> colsToIgnore)
    Weakly-connected components of a sub-matrix.
    void
    Sets all entries in the matrix to zero.
    static Matrix
    zeros(int rows, int cols)
    Creates a matrix of the specified shape filled with zeros.

    Methods inherited from class java.lang.Object

    clone, finalize, getClass, notify, notifyAll, wait, wait, wait
  • Constructor Details

    • Matrix

      public Matrix(int numRows, int numCols, int arrayLength)
      Creates a sparse matrix with the specified dimensions and capacity.
      Parameters:
      numRows - number of rows in the matrix
      numCols - number of columns in the matrix
      arrayLength - initial capacity for non-zero elements
    • Matrix

      public Matrix(int numRows, int numCols)
      Creates a sparse matrix with the specified dimensions.
      Parameters:
      numRows - number of rows in the matrix
      numCols - number of columns in the matrix
    • Matrix

      public Matrix(Matrix matrix)
      Creates a copy of the specified matrix.
      Parameters:
      matrix - the matrix to copy
      Throws:
      UnsupportedOperationException - if the matrix type is not supported
    • Matrix

      public Matrix(org.ejml.data.DMatrix matrix)
      Creates a matrix from an EJML DMatrix (sparse).
      Parameters:
      matrix - the EJML sparse matrix to wrap
    • Matrix

      public Matrix(org.ejml.data.DMatrixRMaj matrix)
      Creates a matrix from an EJML DMatrixRMaj (dense).
      Parameters:
      matrix - the EJML dense matrix to wrap
    • Matrix

      public Matrix(double[][] arrays)
      Creates a matrix from a 2D double array. Uses EJML's triplet format for efficient single-pass batch insertion.
      Parameters:
      arrays - 2D array containing the matrix elements
    • Matrix

      public Matrix(Double[][] arrays)
      Creates a matrix from a Kotlin Array type. This constructor enables direct initialization from Kotlin's arrayOf(doubleArrayOf(...)) syntax. Uses EJML's triplet format for efficient single-pass batch insertion.
      Parameters:
      arrays - Kotlin Array containing DoubleArray rows
    • Matrix

      public Matrix(int[] array)
      Creates a column vector from an integer array.
      Parameters:
      array - integer array to convert to column vector
    • Matrix

      public Matrix(double[] array)
      Creates a column vector from a double array.
      Parameters:
      array - double array to convert to column vector
    • Matrix

      public Matrix(List<Double> array)
    • Matrix

      public Matrix(ArrayList<List<Double>> arrays)
    • Matrix

      public Matrix(org.ejml.simple.SimpleMatrix matrix)
    • Matrix

      public Matrix(String matrixString)
      Parse matrix from string in MATLAB or Python formats MATLAB format assumes commas between row elements and semicolon between rows
      Parameters:
      matrixString - input string, e.g., "[10,4;5,9]" or "[[10,4],[4,9]]"
  • Method Details

    • fromRows

      public static Matrix fromRows(List<List<Double>> rows)
      Constructs a Matrix from a list of rows, where each inner list is a row. Static factory because constructor would clash with Matrix(List<Double>) under erasure.
    • allbut

      public static Matrix allbut(Matrix y, int k)
      Returns all elements in a matrix except the first ones
      Parameters:
      y - - a matrix
      k - - a position of an element in the matrix
      Returns:
      - A row vector with all elements of y but ypos
    • broadcastColPlusRow

      public static Matrix broadcastColPlusRow(Matrix colVector, Matrix rowVector)
      Computes the element-wise sum of a column vector and a row vector, producing a matrix where each entry (i, j) is the sum of colVector[i] and rowVector[j]. This is equivalent to broadcasting the column vector along columns and the row vector along rows.
      Parameters:
      colVector - A column vector of size (m x 1)
      rowVector - A row vector of size (1 x n)
      Returns:
      A matrix of size (m x n) where each element is colVector[i] + rowVector[j]
    • cartesian

      public static Matrix cartesian(Matrix matrixA, Matrix matrixB)
      Cartesian product of two matrices. It replicates elements of the first input matrix and pairs them with each row of the second input matrix.
      Parameters:
      matrixA - first input matrix
      matrixB - second input matrix
    • cell2mat

      public static Matrix cell2mat(Map<Integer,Matrix> cellArray)
      Concatenates a collection of matrices stored in a map into a single row vector. Each matrix is flattened in column-major order and concatenated sequentially based on the map's value order. Only non-zero values are inserted to preserve sparse structure.
      Parameters:
      cellArray - A map from integer indices to Matrix objects to be concatenated
      Returns:
      A single-row Matrix containing all elements from the input matrices in sequence
    • cellsum

      public static Matrix cellsum(Map<Integer,Matrix> cellArray)
      Computes the element-wise sum of all matrices stored in a map. Each matrix must have the same dimensions. The matrices are summed in the order of their integer keys (0 to N-1). The result is accumulated in-place for efficiency.
      Parameters:
      cellArray - A map from integer indices to Matrix objects to be summed
      Returns:
      A Matrix representing the element-wise sum of all matrices in the map
      Throws:
      RuntimeException - if the map is empty or if any matrices have incompatible dimensions
    • columnMatrixToDoubleArray

      public static double[] columnMatrixToDoubleArray(Matrix columnMatrix)
      Converts a column matrix (of size m x 1) to a dense double array of length m.
      Parameters:
      columnMatrix - A Matrix with exactly one column
      Returns:
      A double array containing the values from the column matrix
      Throws:
      IllegalArgumentException - if the input matrix does not have exactly one column
    • compare

      public static boolean compare(Matrix A, Matrix B, String op)
      Compares two matrices element-wise using a specified comparison operator. The matrices must have the same dimensions. Supported operators are: "eq", "equal", "lt", "lessthan", "lte", "lessthanequal", "gt", "greater", "gte", "greaterthanequal".
      Parameters:
      A - The first matrix
      B - The second matrix
      op - The comparison operator as a string
      Returns:
      true if the comparison holds for all elements, false otherwise
    • concatColumns

      public static Matrix concatColumns(Matrix left, Matrix right, Matrix out)
      Concatenates two matrices horizontally (column-wise). If either matrix is empty, returns the non-empty matrix. If an output matrix is provided, writes the result into it; otherwise, returns a newly allocated matrix.
      Parameters:
      left - The matrix to appear on the left
      right - The matrix to appear on the right
      out - (Optional) Output matrix to store the result; can be null
      Returns:
      A matrix representing [left | right]
    • concatRows

      public static Matrix concatRows(Matrix top, Matrix bottom, Matrix out)
      Concatenates two matrices vertically (row-wise). If either matrix is empty, returns the non-empty matrix. If an output matrix is provided, writes the result into it; otherwise, returns a newly allocated matrix.
      Parameters:
      top - The matrix to appear on top
      bottom - The matrix to appear below
      out - (Optional) Output matrix to store the result; can be null
      Returns:
      A matrix representing [top; bottom]
    • createLike

      public static Matrix createLike(Matrix B)
      Creates a new empty matrix with the same shape and internal structure as the given matrix. The contents are uninitialized and all values are implicitly zero (sparse).
      Parameters:
      B - The matrix to copy the structure from
      Returns:
      A new matrix with the same dimensions and sparsity structure as B
    • decorate

      public static Matrix decorate(Matrix inspace1, Matrix inspace2)
    • diag

      public static Matrix diag(double... values)
      Creates a square diagonal matrix from the given values. The input values are placed on the main diagonal; all off-diagonal entries are zero.
      Parameters:
      values - The values to place on the diagonal
      Returns:
      A square sparse matrix with values[i] at position (i, i)
    • diagMatrix

      public static Matrix diagMatrix(double[] values)
      Creates a square diagonal matrix from a given array of values. This is a low-level wrapper that constructs a diagonal matrix using EJML internals. Equivalent to placing values[i] at position (i, i) for all i.
      Parameters:
      values - An array of values to place on the main diagonal
      Returns:
      A square sparse matrix with values[i] at position (i, i)
    • diagMatrix

      public static Matrix diagMatrix(Matrix values)
      Creates a square diagonal matrix from the elements of a column or row vector matrix. Each element in the input matrix is placed on the main diagonal of the resulting matrix.
      Parameters:
      values - A matrix interpreted as a vector (either row or column) containing diagonal values
      Returns:
      A square sparse matrix with the input values along the main diagonal
    • diagMatrix

      public static Matrix diagMatrix(Matrix A, double[] values, int offset, int length)
      Creates or fills a square diagonal matrix with the specified values. If the input matrix A is null, a new diagonal matrix is created. Otherwise, the provided matrix A is filled with the diagonal values.
      Parameters:
      A - An optional matrix to be filled with the diagonal values; can be null
      values - The array of values to place on the main diagonal
      offset - The starting index in values to read from
      length - The number of values to place on the diagonal
      Returns:
      A matrix with values[offset + i] placed at position (i, i)
    • elementMinNonZero

      public static double elementMinNonZero(Matrix matrix)
      Returns the smallest non-zero positive element in the given matrix. If no such element exists, returns 0.
      Parameters:
      matrix - The input matrix
      Returns:
      The minimum strictly positive element, or 0 if all elements are zero or negative
    • extract

      public static void extract(Matrix src, int srcX0, int srcX1, int srcY0, int srcY1, Matrix dst, int dstY0, int dstX0)
      Extracts a rectangular submatrix from a source matrix and stores it in a destination matrix. Equivalent to slicing rows [srcY0:srcY1) and columns [srcX0:srcX1) from src.
      Parameters:
      src - The source matrix
      srcX0 - Starting column (inclusive)
      srcX1 - Ending column (exclusive)
      srcY0 - Starting row (inclusive)
      srcY1 - Ending row (exclusive)
      dst - The destination matrix to store the result
      dstY0 - Starting row index in dst
      dstX0 - Starting column index in dst
    • extract

      public static Matrix extract(Matrix src, int srcX0, int srcX1, int srcY0, int srcY1)
      Extracts a rectangular submatrix from the given source matrix. Equivalent to src[srcY0:srcY1, srcX0:srcX1].
      Parameters:
      src - The source matrix
      srcX0 - Starting column (inclusive)
      srcX1 - Ending column (exclusive)
      srcY0 - Starting row (inclusive)
      srcY1 - Ending row (exclusive)
      Returns:
      A new matrix containing the extracted submatrix
    • extractColumn

      public static Matrix extractColumn(Matrix A, int column, Matrix out)
      Extracts a single column from the given matrix.
      Parameters:
      A - The input matrix
      column - The index of the column to extract
      out - (Optional) Matrix to store the output; if null, a new matrix is created
      Returns:
      A matrix containing the extracted column
    • extractColumns

      public static Matrix extractColumns(Matrix A, int col0, int col1)
      Extracts a range of columns from the matrix [col0:col1).
      Parameters:
      A - The source matrix
      col0 - Starting column index (inclusive)
      col1 - Ending column index (exclusive)
      Returns:
      A new matrix containing the specified columns
    • extractColumns

      public static Matrix extractColumns(Matrix A, int col0, int col1, Matrix out)
      Extracts a range of columns from the matrix [col0:col1) into a destination matrix.
      Parameters:
      A - The source matrix
      col0 - Starting column index (inclusive)
      col1 - Ending column index (exclusive)
      out - Output matrix to hold the result
      Returns:
      A matrix with the specified columns
    • extractDiag

      public static void extractDiag(Matrix A, Matrix outputB)
      Extracts the diagonal elements of a matrix and stores them in a destination matrix.
      Parameters:
      A - The source matrix
      outputB - The matrix to store the diagonal values
    • extractRows

      public static Matrix extractRows(Matrix A, int row0, int row1)
      Extracts a range of rows from the matrix [row0:row1).
      Parameters:
      A - The source matrix
      row0 - Starting row index (inclusive)
      row1 - Ending row index (exclusive)
      Returns:
      A matrix containing the specified rows
    • extractRows

      public static Matrix extractRows(Matrix A, int row0, int row1, Matrix out)
      Extracts a range of rows from the matrix [row0:row1) into a destination matrix.
      Parameters:
      A - The source matrix
      row0 - Starting row index (inclusive)
      row1 - Ending row index (exclusive)
      out - (Optional) Output matrix to store the result; can be null
      Returns:
      A matrix containing the extracted rows
    • eye

      public static Matrix eye(int length)
      Creates an identity matrix of given size.
      Parameters:
      length - The number of rows and columns in the identity matrix
      Returns:
      A sparse identity matrix of size length x length
    • factln

      public static Matrix factln(Matrix n)
      Computes the natural logarithm of the factorial (log(x!)) for each element in the input matrix. The input matrix is assumed to contain non-negative integers or values appropriate for factln().
      Parameters:
      n - Input matrix
      Returns:
      A matrix where each element is log(n_i!)
    • findIndexWithZeroSum

      public static List<Integer> findIndexWithZeroSum(Matrix matrix, boolean isRow)
      Finds the indices of all rows or columns in a matrix that have a sum of zero.
      Parameters:
      matrix - The matrix to check
      isRow - If true, checks rows; if false, checks columns
      Returns:
      A list of indices corresponding to zero-sum rows or columns
    • findRows

      public static List<Integer> findRows(Matrix matrix, Matrix row)
      Finds the indices of all rows in a matrix that exactly match a given row vector.
      Parameters:
      matrix - The matrix to search
      row - A 1-row matrix to compare against
      Returns:
      A list of row indices in matrix that match row
    • firstNorm

      public static double firstNorm(Matrix a)
      Computes the 1-norm (maximum absolute column sum) of the matrix.
      Parameters:
      a - The input matrix
      Returns:
      The 1-norm of the matrix
    • getColIndexSum

      public static int getColIndexSum(Map<Integer,Matrix> cellArray)
      Computes the total number of elements across all matrices in a map, summing numRows * numCols for each matrix.
      Parameters:
      cellArray - A map of matrices
      Returns:
      The total number of scalar elements across all matrices
    • getSubMatrix

      public static Matrix getSubMatrix(Matrix sourceMatrix, int x0, int x1, int y0, int y1)
      Extracts a submatrix from the source matrix using zero-based index ranges. The submatrix spans rows [x0:x1) and columns [y0:y1).
      Parameters:
      sourceMatrix - The source matrix
      x0 - Starting row index (inclusive)
      x1 - Ending row index (exclusive)
      y0 - Starting column index (inclusive)
      y1 - Ending column index (exclusive)
      Returns:
      A new matrix containing the specified submatrix
    • infNorm

      public static double infNorm(Matrix a)
      Computes the infinity norm (maximum absolute row sum) of the matrix.
      Parameters:
      a - The input matrix
      Returns:
      The infinity norm of the matrix
    • infinityNorm

      public double infinityNorm()
      Computes the infinity norm of this matrix. The infinity norm is the maximum row sum of absolute values.
      Returns:
      The infinity norm of this matrix
    • extractCols

      public Matrix extractCols(int col0, int col1)
      Extracts a range of columns from this matrix (instance method).
      Parameters:
      col0 - The starting column index (inclusive)
      col1 - The ending column index (exclusive)
      Returns:
      A new matrix containing columns [col0, col1)
    • extractRows

      public Matrix extractRows(int row0, int row1)
      Extracts rows from this matrix (instance method).
      Parameters:
      row0 - The starting row index (inclusive)
      row1 - The ending row index (exclusive)
      Returns:
      A new matrix containing rows [row0, row1)
    • intersect

      public static List<Double> intersect(Matrix matrixA, Matrix matrixB)
      Computes the intersection of scalar values present in two matrices. The result is a list of distinct values that appear in both matrices.
      Parameters:
      matrixA - First input matrix
      matrixB - Second input matrix
      Returns:
      A list of values common to both matrices
    • inv

      public static Matrix inv(Matrix m)
      Computes the inverse of the given matrix. Delegates to the matrix's inv() method.
      Parameters:
      m - The input matrix
      Returns:
      The inverse of the matrix
    • logSum

      public static double logSum(Matrix matrix)
      Computes the sum of the natural logarithms of all elements in the matrix.
      Parameters:
      matrix - The input matrix
      Returns:
      The sum of log(x) over all elements x in the matrix
      Throws:
      ArithmeticException - if any element is ≤ 0
    • logsumexp

      public static double logsumexp(Matrix x)
      Computes log(sum_i exp(x_i)) in a numerically stable way (log-sum-exp trick). This is commonly used in probabilistic computations to avoid underflow.
      Parameters:
      x - Input matrix treated as a vector of values x₁, x₂, ..., xₙ
      Returns:
      The log-sum-exp of the input values
    • lyap

      public static Matrix lyap(Matrix A, Matrix B, Matrix C, Matrix D)
      Computes the solution to the continuous-time Lyapunov equation AX + XAᵀ + Q = 0. Currently redirects to sylv(jline.util.matrix.Matrix, jline.util.matrix.Matrix, jline.util.matrix.Matrix) assuming it implements the solver.
      Parameters:
      A - The matrix A
      B - Ignored
      C - The matrix Q
      D - Ignored
      Returns:
      The solution matrix X
    • dlyap

      public static Matrix dlyap(Matrix A, Matrix B, Matrix C)
      Solves the discrete Sylvester equation A * X * B - X + C = 0. Equivalent to MATLAB's dlyap(A, B, C). Uses the Kronecker product formulation: (kron(B', A) - I) * vec(X) = -vec(C)
      Parameters:
      A - Left coefficient matrix
      B - Right coefficient matrix
      C - Constant matrix
      Returns:
      Solution matrix X
    • matchrow

      public static int matchrow(Matrix matrix, Matrix row)
      Returns the index of the row in the matrix that exactly matches the given row vector.
      Parameters:
      matrix - The matrix to search
      row - A single-row matrix to match
      Returns:
      The index of the matching row, or -1 if no match is found
    • matrixAddVector

      public static Matrix matrixAddVector(Matrix matrix, Matrix vector)
      Adds a vector to each row or column of the matrix, depending on the vector's orientation.
      Parameters:
      matrix - The input matrix
      vector - A column vector (adds to each row) or a row vector (adds to each column)
      Returns:
      A new matrix with the vector added
      Throws:
      RuntimeException - if the vector shape is incompatible with the matrix
    • maxAbsDiff

      public static double maxAbsDiff(Matrix a, Matrix b)
      Computes the maximum relative absolute difference between corresponding elements of two matrices: max(abs((a - b) / b)).
      Parameters:
      a - First matrix
      b - Second matrix (denominator for relative difference)
      Returns:
      The maximum relative absolute difference
    • negative

      public static Matrix negative(Matrix a)
      Negates all elements in the matrix and returns the result. Operates directly on the sparse structure for performance.
      Parameters:
      a - The input matrix
      Returns:
      A new matrix with all values negated
    • oneMinusMatrix

      public static Matrix oneMinusMatrix(Matrix matrix)
      Computes the matrix 1 - A, where diagonal entries become 1 - A(i, i) and off-diagonal entries become -A(i, j).
      Parameters:
      matrix - The input matrix
      Returns:
      A matrix where each element is replaced by (1 - A(i, i)) on the diagonal and -A(i, j) elsewhere
    • oner

      public static Matrix oner(Matrix N, Integer s)
      Decreases a single element of an integer vector by one.
      Parameters:
      N - The input vector
      s - The index to decrement
      Returns:
      A new vector with element s decreased by one, if in bounds
    • oner

      public static Matrix oner(Matrix N, List<Integer> r)
      Decreases multiple elements of an integer vector by one.
      Parameters:
      N - The input vector
      r - A list of indices to decrement
      Returns:
      A new vector with elements at positions in r decreased by one
    • ones

      public static Matrix ones(int rows, int cols)
      Creates a matrix of the given shape filled with ones.
      Parameters:
      rows - Number of rows
      cols - Number of columns
      Returns:
      A matrix of shape (rows x cols) filled with ones
    • pow

      public static Matrix pow(Matrix a, int b)
      Computes the matrix power A^b for a non-negative integer exponent b. This is done by repeated multiplication and assumes b ≥ 0.
      Parameters:
      a - The base matrix
      b - The exponent (must be ≥ 0)
      Returns:
      The matrix a raised to the power b
    • readFromFile

      public static Matrix readFromFile(String fileName)
      Reads a CSV-formatted matrix from a file. Each line is interpreted as a row. Supports numeric values as well as "Inf" and "-Inf".
      Parameters:
      fileName - Path to the CSV file
      Returns:
      A new Matrix containing the data read from the file
      Throws:
      RuntimeException - if the file cannot be read or parsed
    • removeRows

      public static double[][][] removeRows(double[][][] array, Matrix rowsToRemove)
    • removeTrailingNewLine

      public static String removeTrailingNewLine(String str)
    • scaleMult

      public static Matrix scaleMult(Matrix a, double n)
      Multiplies all elements of a matrix by a scalar. (Marked for removal — consider using matrix.scaleEq(n) directly.)
      Parameters:
      a - The input matrix
      n - The scalar multiplier
      Returns:
      A new matrix equal to a * n
    • singleton

      public static Matrix singleton(double value)
      Creates a 1×1 matrix containing a single scalar value.
      Parameters:
      value - The scalar to store in the matrix
      Returns:
      A 1×1 matrix with the given value
    • solve

      public static boolean solve(Matrix a, Matrix b, Matrix x)
      Solves the sparse linear system Ax = b.
      Parameters:
      a - The coefficient matrix A
      b - The right-hand side vector or matrix b
      x - The solution matrix x (output)
      Returns:
      true if a solution was found, false otherwise
    • solveSafe

      public static boolean solveSafe(Matrix a, Matrix b, Matrix x)
      Solves the linear system Ax = b for x, handling singular matrices gracefully. This method does not throw exceptions for singular matrices, instead returning false and filling the result matrix with NaN values to match MATLAB behavior.
      Parameters:
      a - The coefficient matrix A
      b - The right-hand side vector/matrix b
      x - The solution matrix x (output)
      Returns:
      true if a solution was found, false if matrix is singular
    • solveDirect

      public static boolean solveDirect(Matrix a, Matrix b, Matrix x)
      Solves the linear system A*x = b directly using LU decomposition without singularity checks. Faster than solveSafe(jline.util.matrix.Matrix, jline.util.matrix.Matrix, jline.util.matrix.Matrix) for cases where the matrix is known to be non-singular or where the caller handles failures.
      Parameters:
      a - The coefficient matrix A (must be square)
      b - The right-hand side matrix b
      x - The solution matrix x (output)
      Returns:
      true if a solution was found, false if the LU solver failed
    • spectd

      public static Ret.SpectralDecomposition spectd(Matrix A)
      Computes the spectral decomposition of a matrix A using its eigendecomposition. Returns a diagonal matrix of eigenvalues and a cell array of spectral projectors. For diagonalizable matrices: A = V * D * V⁻¹, where D is the spectrum and each projector is v_k * (v_k⁻¹)^T. For defective matrices, falls back to Jordan decomposition or provides approximation.
      Parameters:
      A - The input matrix
      Returns:
      A SpectralDecomposition containing the diagonal spectrum and associated projectors
      Throws:
      RuntimeException - if the matrix cannot be decomposed
    • sumCumprod

      public static double sumCumprod(Matrix matrix)
      Computes the sum of the cumulative product along a row vector. For vector [a, b, c], returns a + ab + abc.
      Parameters:
      matrix - A 1-row matrix (row vector)
      Returns:
      The scalar sum of cumulative products
    • robustLeftDivide

      public static Matrix robustLeftDivide(Matrix A, Matrix B)
      Robust linear solve for A·X = B that handles singular matrices. Tries standard leftMatrixDivide first, falls back to pseudo-inverse on failure.
      Parameters:
      A - Coefficient matrix (may be singular)
      B - Right-hand side matrix
      Returns:
      Solution matrix X
    • sylv

      public static Matrix sylv(Matrix A, Matrix B, Matrix C)
      Solves the Sylvester equation A·X + X·B = -C using a Schur decomposition-based method. Handles the case where B = Aᵀ with a specialized backward solve, otherwise proceeds forward.
      Parameters:
      A - Left coefficient matrix
      B - Right coefficient matrix
      C - Constant matrix
      Returns:
      Solution matrix X
    • tril

      public static Matrix tril(Matrix matrix)
      Returns the lower triangular part of a matrix (zeroing elements above the main diagonal).
      Parameters:
      matrix - The input matrix
      Returns:
      A lower triangular matrix with upper entries set to zero
    • tril

      public static Matrix tril(Matrix matrix, int k)
      Returns the elements on and below the kth diagonal of matrix A. For k = 0, returns the main diagonal and below. For k = -1, returns only below the main diagonal (strict lower triangular). For k = 1, returns the main diagonal, below, and first superdiagonal.
      Parameters:
      matrix - the input matrix
      k - the diagonal offset (0 = main diagonal, -1 = below main, 1 = above main)
      Returns:
      matrix with elements on and below the kth diagonal, others set to zero
    • union

      public static Matrix union(Matrix A, Matrix B)
      Computes the union of two matrices A and B. For each non-zero element in B, overwrites the corresponding value in A. The resulting matrix is a clone of A with B's non-zero entries inserted.
      Parameters:
      A - The base matrix
      B - The matrix whose non-zero entries override A
      Returns:
      A matrix representing the union of A and B
    • uniqueRowIndexes

      public static UniqueRowResult uniqueRowIndexes(Matrix m)
      Finds the indices of unique rows in a matrix without returning a matrix of the unique rows themselves. Returns: - vi: indices of the first occurrence of each unique row - vj_map: maps unique row indices to a list of positions where that row occurs
      Parameters:
      m - The input matrix
      Returns:
      A UniqueRowResult containing index mappings of unique rows
    • uniqueRowIndexesFromColumn

      public static UniqueRowResult uniqueRowIndexesFromColumn(Matrix m, int startCol)
      Identifies unique rows in a matrix starting from a specified column index. Does not return the unique row data itself, only index mappings. Uses string-based keys to handle state spaces that exceed integer hash range.
      Parameters:
      m - The input matrix
      startCol - The column index from which uniqueness is considered
      Returns:
      A UniqueRowResult containing: - vi: indices of first occurrence of each unique row pattern - vj_map: groupings of row indices by unique pattern
    • uniqueRows

      public static UniqueRowResult uniqueRows(Matrix m)
      Finds all unique rows in a matrix and returns the unique sorted rows, along with mapping indices to/from the original matrix. Uses efficient array-based hashing instead of Matrix objects as keys.
      Parameters:
      m - The input matrix
      Returns:
      A UniqueRowResult containing: - the matrix of sorted unique rows, - vi: indices of first occurrences, - vj_map: row groupings in the original matrix
    • weaklyConnect

      public static Set<Set<Integer>> weaklyConnect(Matrix param, Set<Integer> colsToIgnore)
      Weakly-connected components of a sub-matrix. Constructs an undirected graph from the input matrix, ignoring specified columns, and returns the set of weakly connected components.
      Parameters:
      param - Input matrix
      colsToIgnore - Indexes to be ignored
      Returns:
      A set of sets, each representing a weakly connected component
    • zeros

      public static Matrix zeros(int rows, int cols)
      Creates a matrix of the specified shape filled with zeros.
      Parameters:
      rows - Number of rows
      cols - Number of columns
      Returns:
      A zero-initialized matrix of size (rows x cols)
    • absEq

      public void absEq()
    • add

      public Matrix add(Matrix matrix)
      Adds another matrix to this matrix: this + matrix.
      Parameters:
      matrix - The matrix to add
      Returns:
      A new matrix containing the sum
    • add

      public Matrix add(double alpha)
      Adds a scalar multiple of the all-ones matrix to this matrix: this + alpha * 1.
      Parameters:
      alpha - The scalar multiplier
      Returns:
      A new matrix representing the addition
    • add

      public Matrix add(double alpha, Matrix matrix)
      Adds alpha * matrix to this matrix.
      Parameters:
      alpha - The scalar multiplier
      matrix - The matrix to add
      Returns:
      A new matrix containing the result
    • addEq

      public void addEq(double alpha)
      Adds a scalar value to each element of the matrix in-place.
      Parameters:
      alpha - The scalar value to add
    • addEq

      public void addEq(Matrix matrix)
      Adds another matrix to this matrix in-place: this += matrix.
      Parameters:
      matrix - The matrix to add
    • addEq

      public void addEq(double alpha, Matrix matrix)
      Adds alpha * matrix to this matrix in-place: this += alpha * matrix.
      Parameters:
      alpha - The scalar multiplier
      matrix - The matrix to add
    • allEqualToOne

      public boolean allEqualToOne()
      Checks whether all elements in the matrix are equal to 1.
      Returns:
      true if all elements are exactly 1.0, false otherwise
    • any

      public boolean any()
    • apply

      public void apply(double source, double target, String op)
      Applies a conditional element-wise transformation to the matrix. For each element matching a condition based on source and op, the value is replaced with target.

      Supported operations include: "equal", "notequal", "great", "greatequal", "less", "lessequal".

      This method safely handles special cases like zero, NaN, and Infinity.

      Parameters:
      source - The reference value for the comparison
      target - The value to assign if the condition holds
      op - The comparison operator
    • ceil

      public Matrix ceil()
      Returns a new matrix where each element is the ceiling of the corresponding element in this matrix.
      Returns:
      A new matrix with the ceiling applied element-wise.
    • ceilEq

      public Matrix ceilEq()
      Applies the ceiling operation in-place to each element of this matrix.
      Returns:
      This matrix after applying ceiling element-wise.
    • changeSign

      public void changeSign()
      Negates all values in the matrix, in-place.
    • copy

      public Matrix copy()
      Returns a deep copy of this matrix.
      Returns:
      A cloned matrix identical to this one.
    • colIncrease

      public void colIncrease(int col, double a)
    • colon

      public Matrix colon()
      Returns the matrix in column-major order.
      Returns:
      The same matrix interpreted in column-major order.
    • columnMajorOrder

      public Matrix columnMajorOrder()
      Equivalent to the colon operator in MATLAB (:). Flattens the matrix in column-major order into a single column vector.
      Returns:
      A column vector representing the matrix in column-major order.
    • compareMatrix

      public boolean compareMatrix(Matrix matrix)
      Compares this matrix to another matrix for approximate equality. Tolerance is defined by GlobalConstants.FineTol.
      Parameters:
      matrix - The matrix to compare against.
      Returns:
      true if all elements are approximately equal, false otherwise.
    • compatibleSizesAdd

      public Matrix compatibleSizesAdd(Matrix b)
      Performs element-wise addition with shape broadcasting where applicable.
      Parameters:
      b - Matrix to be added.
      Returns:
      Result of the addition with compatible broadcasting.
    • concatCols

      public Matrix concatCols(Matrix other)
      Concatenates this matrix with another matrix horizontally.
      Parameters:
      other - Matrix to concatenate.
      Returns:
      A new matrix with columns of both matrices concatenated.
    • count

      public int count(double val)
      Counts how many elements in the matrix are equal to a specified value.
      Parameters:
      val - Value to count.
      Returns:
      Number of occurrences of the value.
    • countEachRow

      public Matrix countEachRow(double val)
      Counts the number of occurrences of a value in each row of the matrix.
      Parameters:
      val - Value to count.
      Returns:
      A column vector where each entry is the count for the corresponding row.
    • createBlockDiagonal

      public Matrix createBlockDiagonal(Matrix matrix2)
      Creates a block diagonal matrix by placing the current matrix in the top-left and another matrix (if provided) in the bottom-right.
      Parameters:
      matrix2 - The second matrix to place on the block diagonal. Can be null.
      Returns:
      A new block diagonal matrix combining this and matrix2.
    • cumsumViaCol

      public Matrix cumsumViaCol()
      Computes the cumulative sum of the matrix down each column.
      Returns:
      A matrix where each element is the cumulative sum along its column.
    • cumsumViaRow

      public Matrix cumsumViaRow()
      Computes the cumulative sum of the matrix across each row.
      Returns:
      A matrix where each element is the cumulative sum along its row.
    • det

      public double det()
      Computes the determinant of the matrix.
      Returns:
      Determinant value.
    • div

      public Matrix div(Matrix den)
      Performs element-wise division between this matrix and the provided matrix.
      Parameters:
      den - The denominator matrix.
      Returns:
      A new matrix resulting from element-wise division.
    • divEq

      public void divEq(Matrix den)
      Performs in-place element-wise division between this matrix and the provided matrix.
      Parameters:
      den - The denominator matrix.
    • divide

      public void divide(double scalar, Matrix outputB, boolean flag)
      Divides this matrix by a scalar and stores the result in the output matrix.
      Parameters:
      scalar - The scalar divisor.
      outputB - The matrix to store the result.
      flag - If true, performs matrix / scalar; if false, scalar / matrix.
    • divideEq

      public void divideEq(double scalar)
      Performs in-place division of this matrix by a scalar.
      Parameters:
      scalar - The scalar divisor.
    • divideRows

      public void divideRows(double[] diag, int offset)
      Divides each row of this matrix by the corresponding diagonal element (with an offset).
      Parameters:
      diag - Array of diagonal values.
      offset - Starting offset in the diagonal array.
    • eigval

      public Ret.Eigs eigval()
      Computes the eigenvalues of this square matrix.
      Returns:
      A Ret.Eigs object containing the eigenvalues as a column matrix. If the matrix has complex eigenvalues, the result contains NaN values.
    • eig

      public List<org.apache.commons.math3.complex.Complex> eig()
      Computes the eigenvalues of this square matrix, including complex eigenvalues.
      Returns:
      A list of complex eigenvalues (using Apache Commons Math3 Complex class).
    • eigvec

      public Ret.Eigs eigvec()
      Computes the eigenvalues and eigenvectors of this square matrix.
      Returns:
      A Ret.Eigs object containing the eigenvalues and eigenvectors.
    • svd

      public Ret.SVD svd()
      Computes the Singular Value Decomposition (SVD) of this matrix. The decomposition is A = U * S * V^T where: - U contains the left singular vectors - S is a diagonal matrix of singular values - V contains the right singular vectors
      Returns:
      A Ret.SVD object containing U, S (as column vector), and V matrices.
    • expm

      public Matrix expm()
      Computes the matrix exponential. This is a convenience method that delegates to expm_higham().
      Returns:
      The matrix exponential e^A
      Throws:
      IllegalArgumentException - if the matrix is not square
    • expm_higham

      public Matrix expm_higham()
      Computes the matrix exponential using Higham's scaling and squaring method. This is an implementation of the algorithm from: Higham, N.J. (2005). "The scaling and squaring method for the matrix exponential revisited." SIAM Journal on Matrix Analysis and Applications, 26(4), 1179-1193.
      Returns:
      The matrix exponential e^A
      Throws:
      IllegalArgumentException - if the matrix is not square
    • norm1

      public double norm1()
      Computes the 1-norm of the matrix (maximum absolute column sum).
      Returns:
      The 1-norm of the matrix
    • elementDiv

      public Matrix elementDiv(Matrix B)
      Performs element-wise division of this matrix by another matrix.
      Parameters:
      B - The divisor matrix (must match dimensions).
      Returns:
      A new matrix with the result of element-wise division A ./ B.
      Throws:
      IllegalArgumentException - if matrix dimensions do not match.
    • elementDivide

      public Matrix elementDivide(Matrix b)
      Performs element-wise division with another matrix.
      Parameters:
      b - the matrix to divide by
      Returns:
      the result of element-wise division
      Throws:
      RuntimeException - if matrix dimensions do not match
    • elementIncrease

      public Matrix elementIncrease(double val)
      Increases each element of the matrix by a constant value.
      Parameters:
      val - the value to add to each element
      Returns:
      a new matrix with incremented values
    • elementMax

      public double elementMax()
      Returns the maximum value among all elements in the matrix.
      Returns:
      maximum element value
    • elementMaxAbs

      public double elementMaxAbs()
      Returns the maximum absolute value among all elements in the matrix.
      Returns:
      maximum absolute element value
    • elementMin

      public double elementMin()
      Returns the minimum value among all elements in the matrix.
      Returns:
      minimum element value
    • elementMult

      public Matrix elementMult(Matrix B)
      Performs in-place element-wise multiplication with another matrix.
      Parameters:
      B - the matrix to multiply with
      Returns:
      the updated matrix (this)
    • elementMult

      public Matrix elementMult(Matrix B, Matrix output)
      Performs element-wise multiplication with another matrix, storing the result in the given output matrix.
      Parameters:
      B - the matrix to multiply with
      output - the matrix to store the result in (if null, a new matrix is created)
      Returns:
      the result of the element-wise multiplication
    • elementMult

      public double elementMult()
      Computes the product of the elements of a row or column vector.
      Returns:
      the product of all elements
      Throws:
      IllegalArgumentException - if the matrix is not a row or column vector
    • elementMultWithVector

      public Matrix elementMultWithVector(Matrix B)
      Performs element-wise multiplication between this matrix and a row vector. Each row of the matrix is scaled by the corresponding value in the vector.
      Parameters:
      B - the row vector to multiply with
      Returns:
      the result of the element-wise multiplication
    • elementPow

      public Matrix elementPow(double a)
      Raises each non-zero element of the matrix to the specified power.
      Parameters:
      a - the exponent
      Returns:
      a new matrix with powered elements
    • elementPower

      public Matrix elementPower(double t)
      Raises each element of the matrix to the given power.
      Parameters:
      t - the exponent
      Returns:
      a new matrix with each element raised to the power of t
    • elementSum

      public double elementSum()
      Computes the sum of all elements in the matrix.
      Returns:
      the sum of all elements
    • equals

      public boolean equals(Object obj)
      Checks for matrix equality.
      Overrides:
      equals in class Object
      Parameters:
      obj - the object to compare with
      Returns:
      true if matrices are equal, false otherwise
    • exp

      public Matrix exp()
      Applies the exponential function to each element of the matrix.
      Returns:
      a new matrix with exponentiated elements
    • expandMatrix

      public void expandMatrix(int rows, int cols, int nz_length)
      Expands the matrix dimensions to the specified size while preserving data.
      Parameters:
      rows - new row count
      cols - new column count
      nz_length - estimated non-zero count
    • expandMatrixToSquare

      public void expandMatrixToSquare()
      Expands the matrix to be square, padding with zeros as needed.
    • fact

      public Matrix fact()
      Computes the factorial of each element in the matrix. Equivalent to exp(factln()).
      Returns:
      a matrix with the factorial of each element
    • factln

      public Matrix factln()
      Computes the natural logarithm of the factorial for each element.
      Returns:
      a matrix where each element is the log-factorial of the original element
    • fill

      public Matrix fill(double val)
      Fills all entries in the matrix with the given value.
      Parameters:
      val - the value to fill with
      Returns:
      this matrix after filling
    • find

      public Matrix find()
      Returns the linear indices of all non-zero elements in the matrix.
      Returns:
      a column vector containing indices of non-zero entries
    • findNonNegative

      public Matrix findNonNegative()
      Returns the linear indices of all elements that are non-negative (≥ 0).
      Returns:
      a column vector of indices for non-negative elements
    • findNonZeroRowsInColumn

      public List<Integer> findNonZeroRowsInColumn(int column)
      Finds all row indices in a given column where the value is non-zero.
      Parameters:
      column - the column index to check
      Returns:
      a list of row indices with non-zero values in the given column
    • findNumber

      public Matrix findNumber(double number)
      Finds all linear indices where the matrix has a specific value.
      Parameters:
      number - the value to search for
      Returns:
      a matrix containing the linear indices where the value matches
    • findZero

      public Matrix findZero()
      Finds all linear indices where the matrix value is zero.
      Returns:
      a matrix containing the linear indices of zero-valued elements
    • fromArray2D

      public Matrix fromArray2D(int[][] matrix)
      Populates the matrix from a 2D integer array.
      Parameters:
      matrix - 2D array of integers
      Returns:
      this matrix after population
    • fromArray2D

      public Matrix fromArray2D(double[][] matrix)
      Populates the matrix from a 2D double array.
      Parameters:
      matrix - 2D array of doubles
      Returns:
      this matrix after population
    • get

      public double get(int i, int j)
      Returns the value at the specified row and column.
      Parameters:
      i - row index
      j - column index
      Returns:
      value at (i, j)
    • get

      public double get(int idx)
      Returns the value at the specified index. For vectors (either row or column), returns the idx-th element. For matrices, returns the value at the flattened index (column-major).
      Parameters:
      idx - absolute index
      Returns:
      value at index
    • getColIndexes

      public int[] getColIndexes()
      Returns internal column index array from the sparse matrix structure.
      Returns:
      array of column indexes
    • getColMax

      public int getColMax(int col)
      Returns the row index of the maximum value in the specified column.
      Parameters:
      col - column index
      Returns:
      row index of maximum value
    • getColumn

      public Matrix getColumn(int j)
      Returns a column of the matrix as a new single-column matrix.
      Parameters:
      j - column index
      Returns:
      column matrix
    • getColumnView

      public ColumnView getColumnView(int j)
      Returns a lightweight view into the specified column without copying data. This is much more efficient than getColumn() for large sparse matrices as it doesn't create a new Matrix object or copy any data.

      Use this when you need to iterate through column elements or perform operations that don't require a full Matrix object.

      Parameters:
      j - column index
      Returns:
      a ColumnView providing efficient access to the column
    • getData

      public org.ejml.data.DMatrix getData()
    • setData

      public void setData(org.ejml.data.DMatrix newData)
    • getNonZeroCols

      public int[] getNonZeroCols()
      Returns an array of unique column indices containing non-zero elements.
      Returns:
      array of column indices
    • getNonZeroLength

      public int getNonZeroLength()
      Returns the number of non-zero values in the matrix.
      Returns:
      number of non-zero elements
    • getNonZeroRows

      public int[] getNonZeroRows()
      Returns array of row indices of non-zero entries.
      Returns:
      array of row indices
    • getNonZeroValues

      public double[] getNonZeroValues()
      Returns array of non-zero values in the matrix.
      Returns:
      array of non-zero values
    • getNonZeros

      public int getNonZeros()
      Returns the number of non-zero elements in this matrix.
      Returns:
      the number of non-zero elements
    • getNumCols

      public int getNumCols()
      Returns the number of columns in this matrix.
      Returns:
      the number of columns
    • getNumElements

      public int getNumElements()
      Returns total number of elements in the matrix.
      Returns:
      total element count
    • getNumNonZeros

      public int getNumNonZeros()
    • getNumRows

      public int getNumRows()
      Returns the number of rows in this matrix.
      Returns:
      the number of rows
    • getRow

      public Matrix getRow(int i)
      Returns the specified row as a single-row matrix.
      Parameters:
      i - row index
      Returns:
      row matrix
    • getRowMax

      public int getRowMax(int row)
      Returns column index of maximum element in a specified row.
      Parameters:
      row - the row index
      Returns:
      column index of max value
    • getRowView

      public RowView getRowView(int i)
      Returns a lightweight view into the specified row without copying data. This is much more efficient than getRow() for large sparse matrices as it doesn't create a new Matrix object or copy any data.

      Use this when you need to iterate through row elements or perform operations that don't require a full Matrix object.

      Parameters:
      i - row index
      Returns:
      a RowView providing efficient access to the row
    • getRowsFrom

      public Matrix getRowsFrom(int row)
      Returns a new matrix consisting of rows from the given start index to the end.
      Parameters:
      row - starting row index
      Returns:
      matrix slice
    • getSlice

      public Matrix getSlice(int r0, int r1, int c0, int c1)
      Extracts a submatrix based on row/column bounds.
      Parameters:
      r0 - start row
      r1 - end row (exclusive)
      c0 - start column
      c1 - end column (exclusive)
      Returns:
      submatrix
    • getSlice

      public Matrix getSlice(boolean[] rowFlags, boolean[] colFlags)
      Extracts a submatrix from rows/columns marked as true in input flags.
      Parameters:
      rowFlags - boolean array for rows
      colFlags - boolean array for columns
      Returns:
      submatrix
    • getSubMatrix

      public Matrix getSubMatrix(Matrix rows, Matrix cols)
      Returns a matrix consisting of rows and columns selected by two index matrices.
      Parameters:
      rows - matrix of row indices
      cols - matrix of column indices
      Returns:
      submatrix
    • growMaxColumns

      public void growMaxColumns(int newmax, boolean preserve)
      Increases the internal column capacity of the matrix.
      Parameters:
      newmax - new max columns
      preserve - true if data should be preserved
    • growMaxLength

      public void growMaxLength(int newmax, boolean preserve)
      Increases the internal non-zero element capacity of the matrix.
      Parameters:
      newmax - new max size
      preserve - true if data should be preserved
    • hadamard

      public Matrix hadamard(Matrix B)
      Performs the Hadamard (element-wise) product of two matrices.
      Parameters:
      B - the other matrix
      Returns:
      matrix resulting from element-wise multiplication
    • hasDuplicates

      public boolean hasDuplicates()
    • hasFinite

      public boolean hasFinite()
    • hasInfinite

      public boolean hasInfinite()
    • hasMultipleFinite

      public boolean hasMultipleFinite()
    • hasNaN

      public boolean hasNaN()
    • hashCode

      public int hashCode()
      Generates a hash code for the matrix based on its values.
      Overrides:
      hashCode in class Object
      Returns:
      hash code
    • insertSubMatrix

      public void insertSubMatrix(int start_row, int start_col, int end_row, int end_col, Matrix matrix_to_be_inserted)
      Inserts a sub-matrix into the current matrix at the specified location.
      Parameters:
      start_row - Starting row index
      start_col - Starting column index
      end_row - Ending row index
      end_col - Ending column index
      matrix_to_be_inserted - Matrix to insert
    • inv

      public Matrix inv()
      Computes the inverse of the matrix.
      Returns:
      the inverse matrix
    • pinv

      public Matrix pinv()
      Computes the Moore-Penrose pseudo-inverse of the matrix using SVD. Works for singular, rank-deficient, and non-square matrices. For full-rank square matrices, this is equivalent to inv().
      Returns:
      the pseudo-inverse matrix
    • isAssigned

      public boolean isAssigned(int row, int col)
      Checks whether a specific element is assigned in the sparse matrix.
      Parameters:
      row - Row index
      col - Column index
      Returns:
      true if assigned, false otherwise
    • isDiag

      public boolean isDiag()
      Determines whether the matrix is a diagonal matrix. Zero matrices are not considered diagonal in this implementation.
      Returns:
      true if diagonal, false otherwise
    • isEmpty

      public boolean isEmpty()
      Checks if the matrix is empty (has zero rows or columns).
      Returns:
      true if empty, false otherwise
    • isEqualTo

      public boolean isEqualTo(Matrix m)
      Checks if two matrices are exactly equal.
      Parameters:
      m - the matrix to compare
      Returns:
      true if equal, false otherwise
    • isEqualToTol

      public boolean isEqualToTol(Matrix m, double tol)
      Checks if two matrices are equal within a specified tolerance.
      Parameters:
      m - matrix to compare
      tol - tolerance value
      Returns:
      true if equal within tolerance, false otherwise
    • isFinite

      public boolean isFinite()
      Checks whether all matrix elements are finite.
      Returns:
      true if all elements are finite, false otherwise
    • isInteger

      public boolean isInteger()
      Checks if all values in the matrix are integers.
      Returns:
      true if all values are integers, false otherwise
    • keepCols

      public void keepCols(Collection<Integer> cols)
      Keeps only the specified columns in the matrix. Any column not listed will be removed. For better performance, prefer passing a HashSet for `cols`.
      Parameters:
      cols - Collection of column indices to retain
    • keepRows

      public void keepRows(Collection<Integer> rows)
      Keeps only the specified rows in the matrix. Any row not listed will be removed. For better performance, prefer passing a HashSet for `rows`.
      Parameters:
      rows - Collection of row indices to retain
    • kron

      public Matrix kron(Matrix b)
      Computes the Kronecker product of this matrix and another matrix.
      Parameters:
      b - The matrix to compute the Kronecker product with
      Returns:
      The Kronecker product matrix
    • krons

      public Matrix krons(Matrix other)
      Computes the Kronecker sum of two matrices: A ⊕ B = A \otimes I + I \otimes B, where \otimes is the Kronecker product and I is the identity matrix of matching size.
      Parameters:
      other - The other matrix
      Returns:
      The Kronecker sum of this matrix and the other matrix
    • leftMatrixDivide

      public Matrix leftMatrixDivide(Matrix b)
      Solves the equation AX = B for X, where A is this matrix and B is the right-hand side. For square matrices, this solves the exact system. For rectangular matrices (overdetermined), this computes the least squares solution using the normal equation: X = (A^T * A)^-1 * A^T * B.
      Parameters:
      b - The right-hand side matrix
      Returns:
      The solution matrix X
    • length

      public int length()
      Returns the length of the matrix, defined as max(rows, cols).
      Returns:
      The maximum dimension of the matrix
    • log

      public Matrix log()
      Applies the natural logarithm element-wise.
      Returns:
      A new matrix with log applied to each element
    • meanCol

      public Matrix meanCol()
      Computes the mean of each column.
      Returns:
      A 1xN matrix containing the mean of each column
    • meanRow

      public Matrix meanRow()
      Computes the mean of each row.
      Returns:
      An Nx1 matrix containing the mean of each row
    • mulByMinusOne

      public void mulByMinusOne()
      Multiplies all elements in the matrix by -1 in-place.
    • mult

      public Matrix mult(Matrix B)
      Performs matrix multiplication: this * B
      Parameters:
      B - The right-hand side matrix
      Returns:
      Resultant matrix
    • mult

      public Matrix mult(Matrix B, Matrix out)
      Performs matrix multiplication: this * B
      Parameters:
      B - The right-hand side matrix
      out - Output matrix to write result to (can be null)
      Returns:
      Resultant matrix
    • multColumnView

      public double multColumnView(ColumnView columnView)
      Efficiently multiplies this row vector with a column view. This is optimized for the common pattern: rowVector.mult(matrix.getColumn(j)) by avoiding the creation of intermediate Matrix objects.
      Parameters:
      columnView - the column view to multiply with
      Returns:
      the scalar result of the multiplication
      Throws:
      IllegalArgumentException - if this matrix is not a row vector or dimensions don't match
    • multEq

      public void multEq(Matrix B)
      Replaces this matrix with the result of this * B.
      Parameters:
      B - The right-hand side matrix
    • multRowView

      public double multRowView(RowView rowView)
      Efficiently multiplies a row view with this column vector. This is optimized for the common pattern: matrix.getRow(i).mult(columnVector) by avoiding the creation of intermediate Matrix objects.
      Parameters:
      rowView - the row view to multiply with
      Returns:
      the scalar result of the multiplication
      Throws:
      IllegalArgumentException - if this matrix is not a column vector or dimensions don't match
    • norm

      public double norm()
      Computes the Euclidean norm of a matrix
      Returns:
      - the Euclidean norm of the given matrix
    • normFrobenius

      public double normFrobenius()
      Computes the Frobenius norm of a matrix (alias for norm()).
      Returns:
      - the Frobenius norm of the given matrix
    • ones

      public void ones()
      Fills the matrix with ones. Matrix must already be initialized with correct size. Throws an exception if matrix cannot be fully filled.
    • powerSumCols

      public double powerSumCols(int col, double alpha)
      Computes the sum of powers of absolute values in a column: ∑ |A_{ji}|^alpha
      Parameters:
      col - The column index
      alpha - The exponent to raise each absolute value
      Returns:
      The computed sum
    • powerSumRows

      public double powerSumRows(int row, double alpha)
      Computes the sum of powers of absolute values in a row: ∑ |A_{ij}|^alpha
      Parameters:
      row - The row index
      alpha - The exponent to raise each absolute value
      Returns:
      The computed sum
    • prettyPrint

      public void prettyPrint()
      Pretty prints the matrix with automatic formatting and alignment. Supports real, NaN, Inf, and -Inf values.
    • prettyPrintInt

      public void prettyPrintInt()
      Pretty prints the matrix assuming integer values.
    • print

      public void print()
      Prints the matrix with appropriate formatting, either as floats or integers.
    • printNonZero

      public void printNonZero()
      Prints only non-zero values and their positions in the matrix.
    • qr

      public Map<String,Matrix> qr()
      Performs QR decomposition on the matrix. Only square matrices are currently supported.
      Returns:
      A map containing "Q" and "R" matrices from the decomposition.
    • randMatrix

      public void randMatrix(int length)
      Fills the matrix with random values between 0 and 1.
      Parameters:
      length - The number of rows and columns in the square matrix.
    • rank

      public int rank()
      Computes the rank of the matrix.
      Returns:
      The rank of the matrix.
    • reciprocal

      public Matrix reciprocal()
      Computes the element-wise reciprocal (1/x) of the matrix.
      Returns:
      A new matrix with reciprocal values.
    • remove

      public void remove(int row, int col)
      Removes a specific element from the matrix at the given row and column.
      Parameters:
      row - The row index
      col - The column index
    • removeCols

      public void removeCols(Collection<Integer> cols)
      Removes the specified columns from the matrix. It is recommended to use a HashSet for efficiency when checking column indices.
      Parameters:
      cols - The indices of columns to be removed.
    • removeInfinite

      public void removeInfinite()
      Replaces all infinite values (positive or negative) in the matrix with 0. Also adjusts internal bookkeeping fields to maintain structural integrity.
    • removeInfinity

      public void removeInfinity()
      Removes all infinite values (positive or negative) from the sparse matrix structure. This shifts remaining values to preserve compactness.
    • removeNaN

      public void removeNaN()
      Removes all NaN values from the matrix structure. Internal arrays are compacted and updated accordingly.
    • removeNegative

      public void removeNegative()
      Removes all negative values from the matrix structure. Shifts non-negative values to preserve compactness.
    • removeRows

      public void removeRows(Collection<Integer> rows)
      Removes the specified rows from the matrix. If possible, use a HashSet for better performance.
      Parameters:
      rows - the indices of the rows to be removed
    • removeZeros

      public void removeZeros(double val)
      Removes values from the matrix that are equal to the specified value.
      Parameters:
      val - the value to be removed (typically 0)
    • replace

      public void replace(double delete, double replacement)
      Replaces all occurrences of a specific value with a new value in the matrix. Uses optimized sparse iteration when replacing non-zero values.
      Parameters:
      delete - the value to be replaced
      replacement - the value to insert in place of the deleted value
    • repmat

      public Matrix repmat(int rows, int cols)
      Repeats the matrix to match the specified row and column replication.
      Parameters:
      rows - number of times to repeat along the row dimension
      cols - number of times to repeat along the column dimension
      Returns:
      a new matrix formed by repeating this matrix
    • reshape

      public void reshape(int numRows, int numCols)
      Reshapes the matrix to the specified number of rows and columns.
      Parameters:
      numRows - number of rows
      numCols - number of columns
    • reshape

      public void reshape(int numRows, int numCols, int arrayLength)
      Reshapes the matrix with new dimensions and internal storage length.
      Parameters:
      numRows - number of rows
      numCols - number of columns
      arrayLength - number of non-zero entries the matrix can store
    • reverse

      public Matrix reverse()
      Reverses the elements of a vector (row or column) matrix. Equivalent to MATLAB's v(end:-1:1).
      Returns:
      a matrix with reversed elements
    • reverseRows

      public Matrix reverseRows()
      Reverses the order of rows in the matrix.
      Returns:
      a new matrix with rows in reverse order
    • rightMatrixDivide

      public Matrix rightMatrixDivide(Matrix b)
      Performs right matrix division A / B = A * inv(B)
      Parameters:
      b - the matrix to divide by (on the right)
      Returns:
      result of A / B
    • rowIncrease

      public void rowIncrease(int row, double a)
      Increases all elements in the specified row by a scalar value.
      Parameters:
      row - the row to modify
      a - the scalar to add to each element in the row
    • safeMult

      public Matrix safeMult(Matrix B)
    • scale

      public Matrix scale(double scalar)
      Scales the matrix by the given scalar value.
      Parameters:
      scalar - the value to scale each element by
      Returns:
      a new matrix scaled by the scalar
    • neg

      public Matrix neg()
      Returns the negation of this matrix (all elements multiplied by -1).
      Returns:
      a new matrix with all elements negated
    • scaleEq

      public void scaleEq(double scalar)
      Scales this matrix in-place by the given scalar value.
      Parameters:
      scalar - the value to scale each element by
    • scaleEq

      public void scaleEq(double scalar, Matrix output)
      Scales this matrix by the given scalar value and stores the result in the provided output matrix.
      Parameters:
      scalar - the scalar multiplier
      output - the matrix to store the result
    • schur

      public Map<String,Matrix> schur(String method, Integer iter)
      Computes the Schur decomposition of the matrix.
      Parameters:
      method - method name, currently only "default" is supported
      iter - number of iterations for the default method (null for default=1)
      Returns:
      a map containing the keys "T" (upper triangular matrix) and "U" (unitary matrix)
    • schur

      public Map<String,Matrix> schur()
      Computes the Schur decomposition with the default method and iteration count.
      Returns:
      a map with matrices "T" and "U" from the Schur decomposition
    • schurComplex

      public Map<String,ComplexMatrix> schurComplex()
      Computes the complex Schur decomposition of this matrix, equivalent to MATLAB's schur(A,'complex'). The result has a truly upper-triangular T matrix with complex eigenvalues on the diagonal.

      The method first computes the real Schur decomposition (which may have 2x2 blocks on the diagonal for complex eigenvalue pairs), then converts each 2x2 block to upper-triangular form using unitary Givens rotations.

      Returns:
      a map with keys "U" (ComplexMatrix, unitary) and "T" (ComplexMatrix, upper triangular)
    • set

      public void set(int idx, double val)
      Sets the element at absolute index position to the given value.
      Parameters:
      idx - index in flattened format (row + col * numRows)
      val - value to set
    • set

      public void set(int row, int col, double val)
      Sets the element at specified row and column. Removes the entry if the value is zero to maintain sparse representation.
      Parameters:
      row - row index
      col - column index
      val - value to set
    • set

      public void set(int row, int col, int val)
      Sets the element at specified row and column using an integer value. Interprets Integer.MAX_VALUE as +Inf, MIN_VALUE as -Inf.
      Parameters:
      row - row index
      col - column index
      val - value to set
    • setColumn

      public Matrix setColumn(int j, Matrix col)
      Sets the specified column to the values in the given vector.
      Parameters:
      j - the index of the column to set
      col - the column vector to copy from
      Returns:
      this matrix after the operation
    • setColumns

      public Matrix setColumns(int j0, int j1, Matrix cols)
      Sets multiple columns starting from column index j0 to j1 (exclusive) using values from another matrix.
      Parameters:
      j0 - starting column index (inclusive)
      j1 - ending column index (exclusive)
      cols - the matrix containing new column values
      Returns:
      this matrix after the operation
    • setNaNTo

      public void setNaNTo(double val)
      Replaces all NaN entries in the matrix with the specified value.
      Parameters:
      val - value to replace NaNs with
    • setNaNToZero

      public void setNaNToZero()
      Replaces all NaN entries in the matrix with zero.
    • setRow

      public Matrix setRow(int j, Matrix row)
      Sets the specified row to the values in the given vector.
      Parameters:
      j - the index of the row to set
      row - the row vector to copy from
      Returns:
      this matrix after the operation
    • setRows

      public Matrix setRows(int i0, int i1, Matrix rows)
      Sets multiple rows starting from row index i0 to i1 (exclusive) using values from another matrix.
      Parameters:
      i0 - starting row index (inclusive)
      i1 - ending row index (exclusive)
      rows - the matrix containing new row values
      Returns:
      this matrix after the operation
    • setSlice

      public Matrix setSlice(int rowStart, int rowEnd, int colStart, int colEnd, Matrix newSlice)
      Returns a new matrix representing the updated slice after assigning values from newSlice.
      Parameters:
      rowStart - starting row index (inclusive)
      rowEnd - ending row index (exclusive)
      colStart - starting column index (inclusive)
      colEnd - ending column index (exclusive)
      newSlice - the matrix containing the new values
      Returns:
      the updated submatrix
    • setSliceEq

      public void setSliceEq(int rowStart, int rowEnd, int colStart, int colEnd, Matrix newSlice)
      Sets the values of a submatrix (in-place) using the specified newSlice matrix.
      Parameters:
      rowStart - starting row index (inclusive)
      rowEnd - ending row index (exclusive)
      colStart - starting column index (inclusive)
      colEnd - ending column index (exclusive)
      newSlice - the matrix to copy values from
    • setTo

      public void setTo(Matrix m)
      Copies the data from another matrix into this matrix.
      Parameters:
      m - the matrix to copy from
    • setToNaN

      public void setToNaN()
      Sets all elements of the matrix to NaN.
    • shrinkNumCols

      public void shrinkNumCols(int newmax)
    • shrinkNumRows

      public void shrinkNumRows(int newmax)
    • sort

      public Matrix sort()
      Returns a new matrix with the non-zero values sorted in ascending order.
      Returns:
      a new matrix with sorted values
    • sortEq

      public Matrix sortEq()
      Sorts the current matrix's non-zero values in place.
      Returns:
      this matrix after sorting
    • sqrt

      public Matrix sqrt()
      Computes the element-wise square root of the matrix.
      Returns:
      the resulting matrix
    • square

      public Matrix square()
      Computes the matrix multiplied by itself.
      Returns:
      the squared matrix
    • sub

      public Matrix sub(double x)
      Subtract a scalar from all elements.
      Parameters:
      x - the scalar value to subtract
      Returns:
      the resulting matrix
    • sub

      public Matrix sub(Matrix matrix)
      Subtracts another matrix.
      Parameters:
      matrix - the matrix to subtract
      Returns:
      the resulting matrix
    • sub

      public Matrix sub(double alpha, Matrix matrix)
      Subtracts alpha-scaled version of the provided matrix.
      Parameters:
      alpha - the scalar multiplier
      matrix - the matrix to subtract
      Returns:
      the resulting matrix
    • subEq

      public void subEq(double x)
      Subtracts a scalar from the current matrix in place.
      Parameters:
      x - the scalar to subtract
    • subEq

      public void subEq(Matrix matrix)
      Subtracts a matrix from the current matrix in place.
      Parameters:
      matrix - the matrix to subtract
    • subEq

      public void subEq(double alpha, Matrix matrix)
      Subtracts a scaled matrix from the current matrix in place.
      Parameters:
      alpha - the scale factor
      matrix - the matrix to subtract
    • sumAbsCols

      public double sumAbsCols(int col)
      Sums the absolute values of the given column.
      Parameters:
      col - the column index
      Returns:
      the sum of absolute values in the column
    • sumAbsRows

      public double sumAbsRows(int row)
      Sums the absolute values of the given row.
      Parameters:
      row - the row index
      Returns:
      the sum of absolute values in the row
    • sumCols

      public double sumCols(int col)
      Sums the elements in the specified column.
      Parameters:
      col - the column index
      Returns:
      the sum of the column values
    • sumCols

      public Matrix sumCols()
      Sums the values in each column and returns the results as a row vector.
      Returns:
      a row vector with column sums
    • sumCols

      public Matrix sumCols(int startRow, int endRow)
      Computes the sum of a subset of rows for each column.
      Parameters:
      startRow - the starting row index (inclusive)
      endRow - the ending row index (exclusive)
      Returns:
      a row vector with the sums of each column over the specified row range
    • sumRows

      public double sumRows(int row)
      Computes the sum of the values in a specific row.
      Parameters:
      row - the row index
      Returns:
      the sum of the row values
    • sumRows

      public Matrix sumRows()
      Computes the sum of each row and returns the result as a column vector.
      Returns:
      a column vector containing the sum of each row
    • sumRows

      public Matrix sumRows(int startCol, int endCol)
      Computes the sum over a subrange of columns for each row.
      Parameters:
      startCol - the starting column (inclusive)
      endCol - the ending column (exclusive)
      Returns:
      a column vector with the row sums over the specified columns
    • sumSubMatrix

      public double sumSubMatrix(int startRow, int endRow, int startCol, int endCol)
      Computes the sum of the values in a rectangular submatrix.
      Parameters:
      startRow - the starting row (inclusive)
      endRow - the ending row (exclusive)
      startCol - the starting column (inclusive)
      endCol - the ending column (exclusive)
      Returns:
      the sum of the submatrix values
    • sumSubMatrix

      public double sumSubMatrix(int[] rowIndexes, int[] colIndexes)
      Computes the sum of a submatrix defined by specific row and column indices.
      Parameters:
      rowIndexes - the array of row indices
      colIndexes - the array of column indices
      Returns:
      the sum of the selected submatrix
    • sumSubMatrix

      public double sumSubMatrix(boolean[] rowIndexes, boolean[] colIndexes)
      Computes the sum of a submatrix defined by boolean selection flags.
      Parameters:
      rowIndexes - boolean array indicating selected rows
      colIndexes - boolean array indicating selected columns
      Returns:
      the sum of the selected submatrix
    • toArray1D

      public double[] toArray1D()
      Converts the matrix to a flat 1D array in row-major order.
      Returns:
      the 1D array representation of the matrix
    • toArray2D

      public double[][] toArray2D()
      Converts the matrix to a 2D array representation.
      Returns:
      the 2D array representation of the matrix
    • toDMatrixSparseCSC

      public org.ejml.data.DMatrixSparseCSC toDMatrixSparseCSC()
      Converts this matrix to a copy of its underlying DMatrixSparseCSC structure.
      Returns:
      a deep copy of the internal sparse matrix representation
    • toDMatrixSparseCSC

      public org.ejml.data.DMatrixSparseCSC toDMatrixSparseCSC(Matrix matrix)
      Converts a specified matrix to a copy of its underlying DMatrixSparseCSC structure.
      Parameters:
      matrix - the matrix to convert
      Returns:
      a deep copy of the sparse matrix representation of the given matrix
    • toDouble

      public Double toDouble()
      Converts this matrix to a single Double value. Assumes the matrix is scalar (1x1), otherwise behavior is undefined.
      Returns:
      the single value contained in the matrix
    • toDoubleList

      public List<List<Double>> toDoubleList()
      Converts the matrix to a nested list of Double values.
      Returns:
      a list of lists representing rows and columns of the matrix
    • toIntArray1D

      public int[] toIntArray1D()
      Converts the matrix to a 1D array of int, flattening in row-major order.
      Returns:
      a 1D int array representing the matrix values cast to integers
    • toList1D

      public List<Double> toList1D()
      Converts the matrix into a 1D List of Double values in row-major order.
      Returns:
      a list containing all matrix elements in row-major order
    • toString

      public String toString()
      Returns a formatted string representation of the matrix. Each row is separated by a semicolon and new line.
      Overrides:
      toString in class Object
      Returns:
      the string representation of the matrix
    • transpose

      public Matrix transpose()
      Computes the transpose of the current matrix.
      Returns:
      a new matrix representing the transpose of this matrix
    • uniqueInCol

      public Matrix uniqueInCol(int colIdx)
      Finds unique integer values in the specified column of the matrix.
      Parameters:
      colIdx - the index of the column to search
      Returns:
      a column matrix of unique integer values found in the specified column
    • uniqueInRow

      public Matrix uniqueInRow(int rowIdx)
      Finds unique integer values in the specified row of the matrix.
      Parameters:
      rowIdx - the index of the row to search
      Returns:
      a column matrix of unique integer values found in the specified row
    • uniqueNonNegativeInCol

      public Matrix uniqueNonNegativeInCol(int colIdx)
      Finds unique positive values (strictly greater than 0) in the specified column.
      Parameters:
      colIdx - the index of the column to search
      Returns:
      a column matrix of unique positive values
    • uniqueNonNegativeInRow

      public Matrix uniqueNonNegativeInRow(int rowIdx)
      Finds unique positive values (strictly greater than 0) in the specified row.
      Parameters:
      rowIdx - the index of the row to search
      Returns:
      a column matrix of unique positive values
    • uniqueNonZerosInCol

      public Matrix uniqueNonZerosInCol(int colIdx)
      Finds unique non-zero values in the specified column.
      Parameters:
      colIdx - the index of the column to search
      Returns:
      a column matrix of unique non-zero values
    • uniqueNonZerosInRow

      public Matrix uniqueNonZerosInRow(int rowIdx)
      Finds unique non-zero values in the specified row.
      Parameters:
      rowIdx - the index of the row to search
      Returns:
      a column matrix of unique non-zero values
    • unsafeSet

      public void unsafeSet(int row, int col, double val)
      Sets a value in the matrix without bounds checking. Use this only if you're certain the row and column are valid.
      Parameters:
      row - the row index
      col - the column index
      val - the value to set
    • value

      public double value()
      Returns the value at position (0, 0). Useful for singleton matrices (1x1).
      Returns:
      the scalar value at the top-left of the matrix
    • zero

      public void zero()
      Sets all entries in the matrix to zero.