Package jline.util.matrix
Class Matrix
java.lang.Object
jline.util.matrix.Matrix
- All Implemented Interfaces:
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
ConstructorsConstructorDescriptionMatrix(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.Creates a matrix from a Kotlin Arraytype. Parse matrix from string in MATLAB or Python formats MATLAB format assumes commas between row elements and semicolon between rowsCreates 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 TypeMethodDescriptionvoidabsEq()add(double alpha) Adds a scalar multiple of the all-ones matrix to this matrix:this + alpha * 1.Addsalpha * matrixto this matrix.Adds another matrix to this matrix:this + matrix.voidaddEq(double alpha) Adds a scalar value to each element of the matrix in-place.voidAddsalpha * matrixto this matrix in-place:this += alpha * matrix.voidAdds another matrix to this matrix in-place:this += matrix.static MatrixReturns all elements in a matrix except the first onesbooleanChecks whether all elements in the matrix are equal to 1.booleanany()voidApplies a conditional element-wise transformation to the matrix.static MatrixbroadcastColPlusRow(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 MatrixCartesian product of two matrices.ceil()Returns a new matrix where each element is the ceiling of the corresponding element in this matrix.ceilEq()Applies the ceiling operation in-place to each element of this matrix.static MatrixConcatenates a collection of matrices stored in a map into a single row vector.static MatrixComputes the element-wise sum of all matrices stored in a map.voidNegates all values in the matrix, in-place.voidcolIncrease(int col, double a) colon()Returns the matrix in column-major order.Equivalent to the colon operator in MATLAB (:).static double[]columnMatrixToDoubleArray(Matrix columnMatrix) Converts a column matrix (of size m x 1) to a dense double array of length m.static booleanCompares two matrices element-wise using a specified comparison operator.booleancompareMatrix(Matrix matrix) Compares this matrix to another matrix for approximate equality.Performs element-wise addition with shape broadcasting where applicable.concatCols(Matrix other) Concatenates this matrix with another matrix horizontally.static MatrixconcatColumns(Matrix left, Matrix right, Matrix out) Concatenates two matrices horizontally (column-wise).static MatrixconcatRows(Matrix top, Matrix bottom, Matrix out) Concatenates two matrices vertically (row-wise).copy()Returns a deep copy of this matrix.intcount(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.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.static MatrixcreateLike(Matrix B) 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 Matrixdoubledet()Computes the determinant of the matrix.static Matrixdiag(double... values) Creates a square diagonal matrix from the given values.static MatrixdiagMatrix(double[] values) Creates a square diagonal matrix from a given array of values.static MatrixdiagMatrix(Matrix values) Creates a square diagonal matrix from the elements of a column or row vector matrix.static MatrixdiagMatrix(Matrix A, double[] values, int offset, int length) Creates or fills a square diagonal matrix with the specified values.Performs element-wise division between this matrix and the provided matrix.voidPerforms in-place element-wise division between this matrix and the provided matrix.voidDivides this matrix by a scalar and stores the result in the output matrix.voiddivideEq(double scalar) Performs in-place division of this matrix by a scalar.voiddivideRows(double[] diag, int offset) Divides each row of this matrix by the corresponding diagonal element (with an offset).static MatrixSolves 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.eigval()Computes the eigenvalues of this square matrix.eigvec()Computes the eigenvalues and eigenvectors of this square matrix.elementDiv(Matrix B) 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.doubleReturns the maximum value among all elements in the matrix.doubleReturns the maximum absolute value among all elements in the matrix.doubleReturns the minimum value among all elements in the matrix.static doubleelementMinNonZero(Matrix matrix) Returns the smallest non-zero positive element in the given matrix.doubleComputes the product of the elements of a row or column vector.Performs in-place element-wise multiplication with another matrix.elementMult(Matrix B, Matrix output) 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.doubleComputes the sum of all elements in the matrix.booleanChecks for matrix equality.exp()Applies the exponential function to each element of the matrix.voidexpandMatrix(int rows, int cols, int nz_length) Expands the matrix dimensions to the specified size while preserving data.voidExpands the matrix to be square, padding with zeros as needed.expm()Computes the matrix exponential.Computes the matrix exponential using Higham's scaling and squaring method.static MatrixExtracts a rectangular submatrix from the given source matrix.static voidExtracts 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 MatrixextractColumn(Matrix A, int column, Matrix out) Extracts a single column from the given matrix.static MatrixextractColumns(Matrix A, int col0, int col1) Extracts a range of columns from the matrix [col0:col1).static MatrixextractColumns(Matrix A, int col0, int col1, Matrix out) Extracts a range of columns from the matrix [col0:col1) into a destination matrix.static voidextractDiag(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 MatrixextractRows(Matrix A, int row0, int row1) Extracts a range of rows from the matrix [row0:row1).static MatrixextractRows(Matrix A, int row0, int row1, Matrix out) Extracts a range of rows from the matrix [row0:row1) into a destination matrix.static Matrixeye(int length) Creates an identity matrix of given size.fact()Computes the factorial of each element in the matrix.factln()Computes the natural logarithm of the factorial for each element.static MatrixComputes 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.find()Returns the linear indices of all non-zero elements in the matrix.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).findNonZeroRowsInColumn(int column) 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.Finds the indices of all rows in a matrix that exactly match a given row vector.findZero()Finds all linear indices where the matrix value is zero.static doubleComputes 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 MatrixConstructs a Matrix from a list of rows, where each inner list is a row.doubleget(int idx) Returns the value at the specified index.doubleget(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 intgetColIndexSum(Map<Integer, Matrix> cellArray) Computes the total number of elements across all matrices in a map, summingnumRows * numColsfor each matrix.intgetColMax(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.getColumnView(int j) Returns a lightweight view into the specified column without copying data.org.ejml.data.DMatrixgetData()int[]Returns an array of unique column indices containing non-zero elements.intReturns the number of non-zero values in the matrix.int[]Returns array of row indices of non-zero entries.intReturns the number of non-zero elements in this matrix.double[]Returns array of non-zero values in the matrix.intReturns the number of columns in this matrix.intReturns total number of elements in the matrix.intintReturns the number of rows in this matrix.getRow(int i) Returns the specified row as a single-row matrix.intgetRowMax(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 MatrixgetSubMatrix(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.voidgrowMaxColumns(int newmax, boolean preserve) Increases the internal column capacity of the matrix.voidgrowMaxLength(int newmax, boolean preserve) Increases the internal non-zero element capacity of the matrix.Performs the Hadamard (element-wise) product of two matrices.booleanbooleaninthashCode()Generates a hash code for the matrix based on its values.booleanbooleanbooleanhasNaN()doubleComputes the infinity norm of this matrix.static doubleComputes the infinity norm (maximum absolute row sum) of the matrix.voidinsertSubMatrix(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.Computes the intersection of scalar values present in two matrices.inv()Computes the inverse of the matrix.static MatrixComputes the inverse of the given matrix.booleanisAssigned(int row, int col) Checks whether a specific element is assigned in the sparse matrix.booleanisDiag()Determines whether the matrix is a diagonal matrix.booleanisEmpty()Checks if the matrix is empty (has zero rows or columns).booleanChecks if two matrices are exactly equal.booleanisEqualToTol(Matrix m, double tol) Checks if two matrices are equal within a specified tolerance.booleanisFinite()Checks whether all matrix elements are finite.booleanChecks if all values in the matrix are integers.voidkeepCols(Collection<Integer> cols) Keeps only the specified columns in the matrix.voidkeepRows(Collection<Integer> rows) Keeps only the specified rows in the matrix.Computes the Kronecker product of this matrix and another matrix.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.intlength()Returns the length of the matrix, defined as max(rows, cols).log()Applies the natural logarithm element-wise.static doubleComputes the sum of the natural logarithms of all elements in the matrix.static doubleComputes log(sum_i exp(x_i)) in a numerically stable way (log-sum-exp trick).static MatrixComputes the solution to the continuous-time Lyapunov equation AX + XAᵀ + Q = 0.static intReturns the index of the row in the matrix that exactly matches the given row vector.static MatrixmatrixAddVector(Matrix matrix, Matrix vector) Adds a vector to each row or column of the matrix, depending on the vector's orientation.static doublemaxAbsDiff(Matrix a, Matrix b) Computes the maximum relative absolute difference between corresponding elements of two matrices: max(abs((a - b) / b)).meanCol()Computes the mean of each column.meanRow()Computes the mean of each row.voidMultiplies all elements in the matrix by -1 in-place.Performs matrix multiplication: this * BPerforms matrix multiplication: this * BdoublemultColumnView(ColumnView columnView) Efficiently multiplies this row vector with a column view.voidReplaces this matrix with the result of this * B.doublemultRowView(RowView rowView) Efficiently multiplies a row view with this column vector.neg()Returns the negation of this matrix (all elements multiplied by -1).static MatrixNegates all elements in the matrix and returns the result.doublenorm()Computes the Euclidean norm of a matrixdoublenorm1()Computes the 1-norm of the matrix (maximum absolute column sum).doubleComputes the Frobenius norm of a matrix (alias for norm()).static MatrixoneMinusMatrix(Matrix matrix) Computes the matrix 1 - A, where diagonal entries become 1 - A(i, i) and off-diagonal entries become -A(i, j).static MatrixDecreases a single element of an integer vector by one.static MatrixDecreases multiple elements of an integer vector by one.voidones()Fills the matrix with ones.static Matrixones(int rows, int cols) Creates a matrix of the given shape filled with ones.pinv()Computes the Moore-Penrose pseudo-inverse of the matrix using SVD.static MatrixComputes the matrix power A^b for a non-negative integer exponent b.doublepowerSumCols(int col, double alpha) Computes the sum of powers of absolute values in a column: ∑ |A_{ji}|^alphadoublepowerSumRows(int row, double alpha) Computes the sum of powers of absolute values in a row: ∑ |A_{ij}|^alphavoidPretty prints the matrix with automatic formatting and alignment.voidPretty prints the matrix assuming integer values.voidprint()Prints the matrix with appropriate formatting, either as floats or integers.voidPrints only non-zero values and their positions in the matrix.qr()Performs QR decomposition on the matrix.voidrandMatrix(int length) Fills the matrix with random values between 0 and 1.intrank()Computes the rank of the matrix.static MatrixreadFromFile(String fileName) Reads a CSV-formatted matrix from a file.Computes the element-wise reciprocal (1/x) of the matrix.voidremove(int row, int col) Removes a specific element from the matrix at the given row and column.voidremoveCols(Collection<Integer> cols) Removes the specified columns from the matrix.voidReplaces all infinite values (positive or negative) in the matrix with 0.voidRemoves all infinite values (positive or negative) from the sparse matrix structure.voidRemoves all NaN values from the matrix structure.voidRemoves all negative values from the matrix structure.static double[][][]removeRows(double[][][] array, Matrix rowsToRemove) voidremoveRows(Collection<Integer> rows) Removes the specified rows from the matrix.static StringvoidremoveZeros(double val) Removes values from the matrix that are equal to the specified value.voidreplace(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.voidreshape(int numRows, int numCols) Reshapes the matrix to the specified number of rows and columns.voidreshape(int numRows, int numCols, int arrayLength) Reshapes the matrix with new dimensions and internal storage length.reverse()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 MatrixrobustLeftDivide(Matrix A, Matrix B) Robust linear solve for A·X = B that handles singular matrices.voidrowIncrease(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.voidscaleEq(double scalar) Scales this matrix in-place by the given scalar value.voidScales this matrix by the given scalar value and stores the result in the provided output matrix.static MatrixMultiplies all elements of a matrix by a scalar.schur()Computes the Schur decomposition with the default method and iteration count.Computes the Schur decomposition of the matrix.Computes the complex Schur decomposition of this matrix, equivalent to MATLAB'sschur(A,'complex').voidset(int idx, double val) Sets the element at absolute index position to the given value.voidset(int row, int col, double val) Sets the element at specified row and column.voidset(int row, int col, int val) Sets the element at specified row and column using an integer value.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.voidsetData(org.ejml.data.DMatrix newData) voidsetNaNTo(double val) Replaces all NaN entries in the matrix with the specified value.voidReplaces all NaN entries in the matrix with zero.Sets the specified row to the values in the given vector.Sets multiple rows starting from row index i0 to i1 (exclusive) using values from another matrix.Returns a new matrix representing the updated slice after assigning values from newSlice.voidsetSliceEq(int rowStart, int rowEnd, int colStart, int colEnd, Matrix newSlice) Sets the values of a submatrix (in-place) using the specified newSlice matrix.voidCopies the data from another matrix into this matrix.voidsetToNaN()Sets all elements of the matrix to NaN.voidshrinkNumCols(int newmax) voidshrinkNumRows(int newmax) static Matrixsingleton(double value) Creates a 1×1 matrix containing a single scalar value.static booleanSolves the sparse linear system Ax = b.static booleansolveDirect(Matrix a, Matrix b, Matrix x) Solves the linear system A*x = b directly using LU decomposition without singularity checks.static booleanSolves the linear system Ax = b for x, handling singular matrices gracefully.sort()Returns a new matrix with the non-zero values sorted in ascending order.sortEq()Sorts the current matrix's non-zero values in place.static Ret.SpectralDecompositionComputes the spectral decomposition of a matrix A using its eigendecomposition.sqrt()Computes the element-wise square root of the matrix.square()Computes the matrix multiplied by itself.sub(double x) Subtract a scalar from all elements.Subtracts alpha-scaled version of the provided matrix.Subtracts another matrix.voidsubEq(double x) Subtracts a scalar from the current matrix in place.voidSubtracts a scaled matrix from the current matrix in place.voidSubtracts a matrix from the current matrix in place.doublesumAbsCols(int col) Sums the absolute values of the given column.doublesumAbsRows(int row) Sums the absolute values of the given row.sumCols()Sums the values in each column and returns the results as a row vector.doublesumCols(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 doublesumCumprod(Matrix matrix) Computes the sum of the cumulative product along a row vector.sumRows()Computes the sum of each row and returns the result as a column vector.doublesumRows(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.doublesumSubMatrix(boolean[] rowIndexes, boolean[] colIndexes) Computes the sum of a submatrix defined by boolean selection flags.doublesumSubMatrix(int[] rowIndexes, int[] colIndexes) Computes the sum of a submatrix defined by specific row and column indices.doublesumSubMatrix(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 MatrixSolves 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.DMatrixSparseCSCConverts this matrix to a copy of its underlyingDMatrixSparseCSCstructure.org.ejml.data.DMatrixSparseCSCtoDMatrixSparseCSC(Matrix matrix) Converts a specified matrix to a copy of its underlyingDMatrixSparseCSCstructure.toDouble()Converts this matrix to a singleDoublevalue.Converts the matrix to a nested list ofDoublevalues.int[]Converts the matrix to a 1D array ofint, flattening in row-major order.toList1D()Converts the matrix into a 1DListofDoublevalues in row-major order.toString()Returns a formatted string representation of the matrix.Computes the transpose of the current matrix.static MatrixReturns the lower triangular part of a matrix (zeroing elements above the main diagonal).static MatrixReturns the elements on and below the kth diagonal of matrix A.static MatrixComputes 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.uniqueNonNegativeInCol(int colIdx) Finds unique positive values (strictly greater than 0) in the specified column.uniqueNonNegativeInRow(int rowIdx) 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.static UniqueRowResultFinds the indices of unique rows in a matrix without returning a matrix of the unique rows themselves.static UniqueRowResultuniqueRowIndexesFromColumn(Matrix m, int startCol) Identifies unique rows in a matrix starting from a specified column index.static UniqueRowResultuniqueRows(Matrix m) Finds all unique rows in a matrix and returns the unique sorted rows, along with mapping indices to/from the original matrix.voidunsafeSet(int row, int col, double val) Sets a value in the matrix without bounds checking.doublevalue()Returns the value at position (0, 0).weaklyConnect(Matrix param, Set<Integer> colsToIgnore) Weakly-connected components of a sub-matrix.voidzero()Sets all entries in the matrix to zero.static Matrixzeros(int rows, int cols) Creates a matrix of the specified shape filled with zeros.
-
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 matrixnumCols- number of columns in the matrixarrayLength- 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 matrixnumCols- number of columns in the 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
Creates a matrix from a Kotlin Arraytype. 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
-
Matrix
-
Matrix
public Matrix(org.ejml.simple.SimpleMatrix matrix) -
Matrix
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
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
Returns all elements in a matrix except the first ones- Parameters:
y- - a matrixk- - a position of an element in the matrix- Returns:
- - A row vector with all elements of y but ypos
-
broadcastColPlusRow
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
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 matrixmatrixB- second input matrix
-
cell2mat
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
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
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
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 matrixB- The second matrixop- The comparison operator as a string- Returns:
- true if the comparison holds for all elements, false otherwise
-
concatColumns
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 leftright- The matrix to appear on the rightout- (Optional) Output matrix to store the result; can be null- Returns:
- A matrix representing [left | right]
-
concatRows
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 topbottom- The matrix to appear belowout- (Optional) Output matrix to store the result; can be null- Returns:
- A matrix representing [top; bottom]
-
createLike
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
-
diag
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
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 placingvalues[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
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
Creates or fills a square diagonal matrix with the specified values. If the input matrixAis null, a new diagonal matrix is created. Otherwise, the provided matrixAis filled with the diagonal values.- Parameters:
A- An optional matrix to be filled with the diagonal values; can be nullvalues- The array of values to place on the main diagonaloffset- The starting index invaluesto read fromlength- The number of values to place on the diagonal- Returns:
- A matrix with
values[offset + i]placed at position (i, i)
-
elementMinNonZero
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) fromsrc.- Parameters:
src- The source matrixsrcX0- Starting column (inclusive)srcX1- Ending column (exclusive)srcY0- Starting row (inclusive)srcY1- Ending row (exclusive)dst- The destination matrix to store the resultdstY0- Starting row index indstdstX0- Starting column index indst
-
extract
Extracts a rectangular submatrix from the given source matrix. Equivalent tosrc[srcY0:srcY1, srcX0:srcX1].- Parameters:
src- The source matrixsrcX0- Starting column (inclusive)srcX1- Ending column (exclusive)srcY0- Starting row (inclusive)srcY1- Ending row (exclusive)- Returns:
- A new matrix containing the extracted submatrix
-
extractColumn
Extracts a single column from the given matrix.- Parameters:
A- The input matrixcolumn- The index of the column to extractout- (Optional) Matrix to store the output; if null, a new matrix is created- Returns:
- A matrix containing the extracted column
-
extractColumns
Extracts a range of columns from the matrix [col0:col1).- Parameters:
A- The source matrixcol0- Starting column index (inclusive)col1- Ending column index (exclusive)- Returns:
- A new matrix containing the specified columns
-
extractColumns
Extracts a range of columns from the matrix [col0:col1) into a destination matrix.- Parameters:
A- The source matrixcol0- Starting column index (inclusive)col1- Ending column index (exclusive)out- Output matrix to hold the result- Returns:
- A matrix with the specified columns
-
extractDiag
Extracts the diagonal elements of a matrix and stores them in a destination matrix.- Parameters:
A- The source matrixoutputB- The matrix to store the diagonal values
-
extractRows
Extracts a range of rows from the matrix [row0:row1).- Parameters:
A- The source matrixrow0- Starting row index (inclusive)row1- Ending row index (exclusive)- Returns:
- A matrix containing the specified rows
-
extractRows
Extracts a range of rows from the matrix [row0:row1) into a destination matrix.- Parameters:
A- The source matrixrow0- 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
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
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 forfactln().- Parameters:
n- Input matrix- Returns:
- A matrix where each element is
log(n_i!)
-
findIndexWithZeroSum
Finds the indices of all rows or columns in a matrix that have a sum of zero.- Parameters:
matrix- The matrix to checkisRow- If true, checks rows; if false, checks columns- Returns:
- A list of indices corresponding to zero-sum rows or columns
-
findRows
Finds the indices of all rows in a matrix that exactly match a given row vector.- Parameters:
matrix- The matrix to searchrow- A 1-row matrix to compare against- Returns:
- A list of row indices in
matrixthat matchrow
-
firstNorm
Computes the 1-norm (maximum absolute column sum) of the matrix.- Parameters:
a- The input matrix- Returns:
- The 1-norm of the matrix
-
getColIndexSum
Computes the total number of elements across all matrices in a map, summingnumRows * numColsfor each matrix.- Parameters:
cellArray- A map of matrices- Returns:
- The total number of scalar elements across all matrices
-
getSubMatrix
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 matrixx0- 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
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
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
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
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 matrixmatrixB- Second input matrix- Returns:
- A list of values common to both matrices
-
inv
Computes the inverse of the given matrix. Delegates to the matrix'sinv()method.- Parameters:
m- The input matrix- Returns:
- The inverse of the matrix
-
logSum
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
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
Computes the solution to the continuous-time Lyapunov equation AX + XAᵀ + Q = 0. Currently redirects tosylv(jline.util.matrix.Matrix, jline.util.matrix.Matrix, jline.util.matrix.Matrix)assuming it implements the solver.- Parameters:
A- The matrix AB- IgnoredC- The matrix QD- Ignored- Returns:
- The solution matrix X
-
dlyap
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 matrixB- Right coefficient matrixC- Constant matrix- Returns:
- Solution matrix X
-
matchrow
Returns the index of the row in the matrix that exactly matches the given row vector.- Parameters:
matrix- The matrix to searchrow- A single-row matrix to match- Returns:
- The index of the matching row, or -1 if no match is found
-
matrixAddVector
Adds a vector to each row or column of the matrix, depending on the vector's orientation.- Parameters:
matrix- The input matrixvector- 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
Computes the maximum relative absolute difference between corresponding elements of two matrices: max(abs((a - b) / b)).- Parameters:
a- First matrixb- Second matrix (denominator for relative difference)- Returns:
- The maximum relative absolute difference
-
negative
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
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
Decreases a single element of an integer vector by one.- Parameters:
N- The input vectors- The index to decrement- Returns:
- A new vector with element
sdecreased by one, if in bounds
-
oner
Decreases multiple elements of an integer vector by one.- Parameters:
N- The input vectorr- A list of indices to decrement- Returns:
- A new vector with elements at positions in
rdecreased by one
-
ones
Creates a matrix of the given shape filled with ones.- Parameters:
rows- Number of rowscols- Number of columns- Returns:
- A matrix of shape (rows x cols) filled with ones
-
pow
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 matrixb- The exponent (must be ≥ 0)- Returns:
- The matrix
araised to the powerb
-
readFromFile
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
-
removeTrailingNewLine
-
scaleMult
Multiplies all elements of a matrix by a scalar. (Marked for removal — consider usingmatrix.scaleEq(n)directly.)- Parameters:
a- The input matrixn- The scalar multiplier- Returns:
- A new matrix equal to
a * n
-
singleton
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
Solves the sparse linear system Ax = b.- Parameters:
a- The coefficient matrix Ab- The right-hand side vector or matrix bx- The solution matrix x (output)- Returns:
- true if a solution was found, false otherwise
-
solveSafe
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 Ab- The right-hand side vector/matrix bx- The solution matrix x (output)- Returns:
- true if a solution was found, false if matrix is singular
-
solveDirect
Solves the linear system A*x = b directly using LU decomposition without singularity checks. Faster thansolveSafe(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 bx- The solution matrix x (output)- Returns:
- true if a solution was found, false if the LU solver failed
-
spectd
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
SpectralDecompositioncontaining the diagonal spectrum and associated projectors - Throws:
RuntimeException- if the matrix cannot be decomposed
-
sumCumprod
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
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
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 matrixB- Right coefficient matrixC- Constant matrix- Returns:
- Solution matrix X
-
tril
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
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 matrixk- 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
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 matrixB- The matrix whose non-zero entries override A- Returns:
- A matrix representing the union of A and B
-
uniqueRowIndexes
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
UniqueRowResultcontaining index mappings of unique rows
-
uniqueRowIndexesFromColumn
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 matrixstartCol- The column index from which uniqueness is considered- Returns:
- A
UniqueRowResultcontaining: - vi: indices of first occurrence of each unique row pattern - vj_map: groupings of row indices by unique pattern
-
uniqueRows
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
UniqueRowResultcontaining: - the matrix of sorted unique rows, - vi: indices of first occurrences, - vj_map: row groupings in the original matrix
-
weaklyConnect
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 matrixcolsToIgnore- Indexes to be ignored- Returns:
- A set of sets, each representing a weakly connected component
-
zeros
Creates a matrix of the specified shape filled with zeros.- Parameters:
rows- Number of rowscols- Number of columns- Returns:
- A zero-initialized matrix of size (rows x cols)
-
absEq
public void absEq() -
add
Adds another matrix to this matrix:this + matrix.- Parameters:
matrix- The matrix to add- Returns:
- A new matrix containing the sum
-
add
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
Addsalpha * matrixto this matrix.- Parameters:
alpha- The scalar multipliermatrix- 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
Adds another matrix to this matrix in-place:this += matrix.- Parameters:
matrix- The matrix to add
-
addEq
Addsalpha * matrixto this matrix in-place:this += alpha * matrix.- Parameters:
alpha- The scalar multipliermatrix- 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
Applies a conditional element-wise transformation to the matrix. For each element matching a condition based onsourceandop, the value is replaced withtarget.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 comparisontarget- The value to assign if the condition holdsop- The comparison operator
-
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
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
Returns a deep copy of this matrix.- Returns:
- A cloned matrix identical to this one.
-
colIncrease
public void colIncrease(int col, double a) -
colon
Returns the matrix in column-major order.- Returns:
- The same matrix interpreted in column-major order.
-
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
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
Performs element-wise addition with shape broadcasting where applicable.- Parameters:
b- Matrix to be added.- Returns:
- Result of the addition with compatible broadcasting.
-
concatCols
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
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
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
Computes the cumulative sum of the matrix down each column.- Returns:
- A matrix where each element is the cumulative sum along its column.
-
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
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
Performs in-place element-wise division between this matrix and the provided matrix.- Parameters:
den- The denominator matrix.
-
divide
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
Computes the eigenvalues of this square matrix.- Returns:
- A
Ret.Eigsobject containing the eigenvalues as a column matrix. If the matrix has complex eigenvalues, the result contains NaN values.
-
eig
Computes the eigenvalues of this square matrix, including complex eigenvalues.- Returns:
- A list of complex eigenvalues (using Apache Commons Math3 Complex class).
-
eigvec
Computes the eigenvalues and eigenvectors of this square matrix.- Returns:
- A
Ret.Eigsobject containing the eigenvalues and eigenvectors.
-
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.SVDobject containing U, S (as column vector), and V matrices.
-
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
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
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
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
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
Performs in-place element-wise multiplication with another matrix.- Parameters:
B- the matrix to multiply with- Returns:
- the updated matrix (this)
-
elementMult
Performs element-wise multiplication with another matrix, storing the result in the given output matrix.- Parameters:
B- the matrix to multiply withoutput- 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
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
Raises each non-zero element of the matrix to the specified power.- Parameters:
a- the exponent- Returns:
- a new matrix with powered elements
-
elementPower
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
Checks for matrix equality. -
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 countcols- new column countnz_length- estimated non-zero count
-
expandMatrixToSquare
public void expandMatrixToSquare()Expands the matrix to be square, padding with zeros as needed. -
fact
Computes the factorial of each element in the matrix. Equivalent toexp(factln()).- Returns:
- a matrix with the factorial of each element
-
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
Fills all entries in the matrix with the given value.- Parameters:
val- the value to fill with- Returns:
- this matrix after filling
-
find
Returns the linear indices of all non-zero elements in the matrix.- Returns:
- a column vector containing indices of non-zero entries
-
findNonNegative
Returns the linear indices of all elements that are non-negative (≥ 0).- Returns:
- a column vector of indices for non-negative elements
-
findNonZeroRowsInColumn
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
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
Finds all linear indices where the matrix value is zero.- Returns:
- a matrix containing the linear indices of zero-valued elements
-
fromArray2D
Populates the matrix from a 2D integer array.- Parameters:
matrix- 2D array of integers- Returns:
- this matrix after population
-
fromArray2D
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 indexj- 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
Returns a column of the matrix as a new single-column matrix.- Parameters:
j- column index- Returns:
- column matrix
-
getColumnView
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
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
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
Returns a new matrix consisting of rows from the given start index to the end.- Parameters:
row- starting row index- Returns:
- matrix slice
-
getSlice
Extracts a submatrix based on row/column bounds.- Parameters:
r0- start rowr1- end row (exclusive)c0- start columnc1- end column (exclusive)- Returns:
- submatrix
-
getSlice
Extracts a submatrix from rows/columns marked as true in input flags.- Parameters:
rowFlags- boolean array for rowscolFlags- boolean array for columns- Returns:
- submatrix
-
getSubMatrix
Returns a matrix consisting of rows and columns selected by two index matrices.- Parameters:
rows- matrix of row indicescols- 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 columnspreserve- 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 sizepreserve- true if data should be preserved
-
hadamard
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. -
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 indexstart_col- Starting column indexend_row- Ending row indexend_col- Ending column indexmatrix_to_be_inserted- Matrix to insert
-
inv
Computes the inverse of the matrix.- Returns:
- the inverse 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 indexcol- 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
Checks if two matrices are exactly equal.- Parameters:
m- the matrix to compare- Returns:
- true if equal, false otherwise
-
isEqualToTol
Checks if two matrices are equal within a specified tolerance.- Parameters:
m- matrix to comparetol- 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
Keeps only the specified columns in the matrix. Any column not listed will be removed. For better performance, prefer passing aHashSetfor `cols`.- Parameters:
cols- Collection of column indices to retain
-
keepRows
Keeps only the specified rows in the matrix. Any row not listed will be removed. For better performance, prefer passing aHashSetfor `rows`.- Parameters:
rows- Collection of row indices to retain
-
kron
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
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
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
Applies the natural logarithm element-wise.- Returns:
- A new matrix with log applied to each element
-
meanCol
Computes the mean of each column.- Returns:
- A 1xN matrix containing the mean of each column
-
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
Performs matrix multiplication: this * B- Parameters:
B- The right-hand side matrix- Returns:
- Resultant matrix
-
mult
Performs matrix multiplication: this * B- Parameters:
B- The right-hand side matrixout- Output matrix to write result to (can be null)- Returns:
- Resultant matrix
-
multColumnView
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
Replaces this matrix with the result of this * B.- Parameters:
B- The right-hand side matrix
-
multRowView
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 indexalpha- 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 indexalpha- 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
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
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 indexcol- The column index
-
removeCols
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
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 replacedreplacement- the value to insert in place of the deleted value
-
repmat
Repeats the matrix to match the specified row and column replication.- Parameters:
rows- number of times to repeat along the row dimensioncols- 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 rowsnumCols- 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 rowsnumCols- number of columnsarrayLength- number of non-zero entries the matrix can store
-
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
Reverses the order of rows in the matrix.- Returns:
- a new matrix with rows in reverse order
-
rightMatrixDivide
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 modifya- the scalar to add to each element in the row
-
safeMult
-
scale
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
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
Scales this matrix by the given scalar value and stores the result in the provided output matrix.- Parameters:
scalar- the scalar multiplieroutput- the matrix to store the result
-
schur
Computes the Schur decomposition of the matrix.- Parameters:
method- method name, currently only "default" is supportediter- 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
Computes the Schur decomposition with the default method and iteration count.- Returns:
- a map with matrices "T" and "U" from the Schur decomposition
-
schurComplex
Computes the complex Schur decomposition of this matrix, equivalent to MATLAB'sschur(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 indexcol- column indexval- 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 indexcol- column indexval- value to set
-
setColumn
Sets the specified column to the values in the given vector.- Parameters:
j- the index of the column to setcol- the column vector to copy from- Returns:
- this matrix after the operation
-
setColumns
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
Sets the specified row to the values in the given vector.- Parameters:
j- the index of the row to setrow- the row vector to copy from- Returns:
- this matrix after the operation
-
setRows
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
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
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
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
Returns a new matrix with the non-zero values sorted in ascending order.- Returns:
- a new matrix with sorted values
-
sortEq
Sorts the current matrix's non-zero values in place.- Returns:
- this matrix after sorting
-
sqrt
Computes the element-wise square root of the matrix.- Returns:
- the resulting matrix
-
square
Computes the matrix multiplied by itself.- Returns:
- the squared matrix
-
sub
Subtract a scalar from all elements.- Parameters:
x- the scalar value to subtract- Returns:
- the resulting matrix
-
sub
Subtracts another matrix.- Parameters:
matrix- the matrix to subtract- Returns:
- the resulting matrix
-
sub
Subtracts alpha-scaled version of the provided matrix.- Parameters:
alpha- the scalar multipliermatrix- 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
Subtracts a matrix from the current matrix in place.- Parameters:
matrix- the matrix to subtract
-
subEq
Subtracts a scaled matrix from the current matrix in place.- Parameters:
alpha- the scale factormatrix- 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
Sums the values in each column and returns the results as a row vector.- Returns:
- a row vector with column sums
-
sumCols
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
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
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 indicescolIndexes- 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 rowscolIndexes- 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 underlyingDMatrixSparseCSCstructure.- Returns:
- a deep copy of the internal sparse matrix representation
-
toDMatrixSparseCSC
Converts a specified matrix to a copy of its underlyingDMatrixSparseCSCstructure.- Parameters:
matrix- the matrix to convert- Returns:
- a deep copy of the sparse matrix representation of the given matrix
-
toDouble
Converts this matrix to a singleDoublevalue. Assumes the matrix is scalar (1x1), otherwise behavior is undefined.- Returns:
- the single value contained in the matrix
-
toDoubleList
Converts the matrix to a nested list ofDoublevalues.- Returns:
- a list of lists representing rows and columns of the matrix
-
toIntArray1D
public int[] toIntArray1D()Converts the matrix to a 1D array ofint, flattening in row-major order.- Returns:
- a 1D int array representing the matrix values cast to integers
-
toList1D
Converts the matrix into a 1DListofDoublevalues in row-major order.- Returns:
- a list containing all matrix elements in row-major order
-
toString
Returns a formatted string representation of the matrix. Each row is separated by a semicolon and new line. -
transpose
Computes the transpose of the current matrix.- Returns:
- a new matrix representing the transpose of this matrix
-
uniqueInCol
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
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
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
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
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
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 indexcol- the column indexval- 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.
-