Class Matrix
-
- All Implemented Interfaces:
-
java.io.Serializable
public final class Matrix 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
-
-
Constructor Summary
Constructors Constructor Description Matrix(int numRows, int numCols, int arrayLength)
Creates a sparse matrix with the specified dimensions and capacity. Matrix(int numRows, int numCols)
Creates a sparse matrix with the specified dimensions. Matrix(Matrix matrix)
Creates a copy of the specified matrix. Matrix(DMatrix matrix)
Creates a matrix from an EJML DMatrix (sparse). Matrix(DMatrixRMaj matrix)
Creates a matrix from an EJML DMatrixRMaj (dense). Matrix(Array<Array<double>> arrays)
Creates a matrix from a 2D double array. Matrix(Array<Array<Double>> arrays)
Creates a matrix from a Kotlin Arraytype. Matrix(Array<int> array)
Creates a column vector from an integer array. Matrix(Array<double> array)
Creates a column vector from a double array. Matrix(List<Double> array)
Matrix(ArrayList<List<Double>> arrays)
Matrix(SimpleMatrix matrix)
Matrix(String matrixString)
Parse matrix from string in MATLAB or Python formats MATLAB format assumes commas between row elements and semicolon between rows
-
Method Summary
Modifier and Type Method Description static Matrix
allbut(Matrix y, int k)
Returns all elements in a matrix except the first ones 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. 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. static Array<double>
columnMatrixToDoubleArray(Matrix columnMatrix)
Converts a column matrix (of size m x 1) to a dense double array of length m. static boolean
compare(Matrix A, Matrix B, String op)
Compares two matrices element-wise using a specified comparison operator. 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). static Matrix
createLike(Matrix B)
Creates a new empty matrix with the same shape and internal structure as the given matrix. static Matrix
decorate(Matrix inspace1, Matrix inspace2)
static Matrix
diag(Array<double> values)
Creates a square diagonal matrix from the given values. static Matrix
diagMatrix(Array<double> values)
Creates a square diagonal matrix from a given array of values. static Matrix
diagMatrix(Matrix values)
Creates a square diagonal matrix from the elements of a column or row vector matrix. static Matrix
diagMatrix(Matrix A, Array<double> values, int offset, int length)
Creates or fills a square diagonal matrix with the specified values. static double
elementMinNonZero(Matrix matrix)
Returns the smallest non-zero positive element in the given 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. static Matrix
extract(Matrix src, int srcX0, int srcX1, int srcY0, int srcY1)
Extracts a rectangular submatrix from the given source matrix. 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. 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. static Matrix
factln(Matrix n)
Computes the natural logarithm of the factorial (log(x!)) for each element in the input 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. static List<Integer>
findRows(Matrix matrix, Matrix row)
Finds the indices of all rows in a matrix that exactly match a given row vector. static double
firstNorm(Matrix a)
Computes the 1-norm (maximum absolute column sum) of the matrix. 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.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. static double
infNorm(Matrix a)
Computes the infinity norm (maximum absolute row sum) of the matrix. static List<Double>
intersect(Matrix matrixA, Matrix matrixB)
Computes the intersection of scalar values present in two matrices. static Matrix
inv(Matrix m)
Computes the inverse of the given matrix. static double
logSum(Matrix matrix)
Computes the sum of the natural logarithms of all elements in the matrix. static double
logsumexp(Matrix x)
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
maxAbsDiff(Matrix a, Matrix b)
Computes the maximum relative absolute difference between corresponding elements of two matrices: max(abs((a - b) / b)). static Matrix
negative(Matrix a)
Negates all elements in the matrix and returns the result. 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). static Matrix
oner(Matrix N, Integer s)
Decreases a single element of an integer vector by one. static Matrix
oner(Matrix N, List<Integer> r)
Decreases multiple elements of an integer vector by one. static Matrix
ones(int rows, int cols)
Creates a matrix of the given shape filled with ones. static Matrix
pow(Matrix a, int b)
Computes the matrix power A^b for a non-negative integer exponent b. static Matrix
readFromFile(String fileName)
Reads a CSV-formatted matrix from a file. static Array<Array<Array<double>>>
removeRows(Array<Array<Array<double>>> array, Matrix rowsToRemove)
static String
removeTrailingNewLine(String str)
static Matrix
scaleMult(Matrix a, double n)
Multiplies all elements of a matrix by a scalar. static Matrix
singleton(double value)
Creates a 1×1 matrix containing a single scalar value. static boolean
solve(Matrix a, Matrix b, Matrix x)
Solves the sparse linear system Ax = b. static boolean
solveSafe(Matrix a, Matrix b, Matrix x)
Solves the linear system Ax = b for x, handling singular matrices gracefully. static Ret.SpectralDecomposition
spectd(Matrix A)
Computes the spectral decomposition of a matrix A using its eigendecomposition. static double
sumCumprod(Matrix matrix)
Computes the sum of the cumulative product along a row vector. static Matrix
sylv(Matrix A, Matrix B, Matrix C)
Solves the Sylvester equation A·X + X·B = -C using a Schur decomposition-based method. 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
union(Matrix A, Matrix B)
Computes the union of two matrices A and B. static UniqueRowResult
uniqueRowIndexes(Matrix m)
Finds the indices of unique rows in a matrix without returning a matrix of the unique rows themselves. static UniqueRowResult
uniqueRowIndexesFromColumn(Matrix m, int startCol)
Identifies unique rows in a matrix starting from a specified column index. 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. static Set<Set<Integer>>
weaklyConnect(Matrix param, Set<Integer> colsToIgnore)
Weakly-connected components of a sub-matrix. static Matrix
zeros(int rows, int cols)
Creates a matrix of the specified shape filled with zeros. void
absEq()
Matrix
add(Matrix matrix)
Adds another matrix to this matrix: this + matrix
.Matrix
add(double alpha)
Adds a scalar multiple of the all-ones matrix to this matrix: this + alpha * 1
.Matrix
add(double alpha, Matrix matrix)
Adds alpha * matrix
to this matrix.void
addEq(double alpha)
Adds a scalar value to each element of the matrix in-place. void
addEq(Matrix matrix)
Adds another matrix to this matrix in-place: this += matrix
.void
addEq(double alpha, Matrix matrix)
Adds alpha * matrix
to this matrix in-place:this += alpha * matrix
.boolean
allEqualToOne()
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. Matrix
ceil()
Returns a new matrix where each element is the ceiling of the corresponding element in this matrix. Matrix
ceilEq()
Applies the ceiling operation in-place to each element of this matrix. void
changeSign()
Negates all values in the matrix, in-place. Matrix
copy()
Returns a deep copy of this matrix. void
colIncrease(int col, double a)
Matrix
colon()
Returns the matrix in column-major order. Matrix
columnMajorOrder()
Equivalent to the colon operator in MATLAB (:). boolean
compareMatrix(Matrix matrix)
Compares this matrix to another matrix for approximate equality. Matrix
compatibleSizesAdd(Matrix b)
Performs element-wise addition with shape broadcasting where applicable. Matrix
concatCols(Matrix other)
Concatenates this matrix with another matrix horizontally. int
count(double val)
Counts how many elements in the matrix are equal to a specified value. Matrix
countEachRow(double val)
Counts the number of occurrences of a value in each row of the matrix. 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. Matrix
cumsumViaCol()
Computes the cumulative sum of the matrix down each column. Matrix
cumsumViaRow()
Computes the cumulative sum of the matrix across each row. double
det()
Computes the determinant of the matrix. Matrix
div(Matrix den)
Performs element-wise division between this matrix and the provided matrix. void
divEq(Matrix den)
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(Array<double> diag, int offset)
Divides each row of this matrix by the corresponding diagonal element (with an offset). Ret.Eigs
eigval()
Computes the eigenvalues of this square matrix. Ret.Eigs
eigvec()
Computes the eigenvalues and eigenvectors of this square matrix. Matrix
expm_higham()
Computes the matrix exponential using Higham's scaling and squaring method. double
norm1()
Computes the 1-norm of the matrix (maximum absolute column sum). Matrix
elementDiv(Matrix B)
Performs element-wise division of this matrix by another matrix. Matrix
elementDivide(Matrix b)
Performs element-wise division with another matrix. Matrix
elementIncrease(double val)
Increases each element of the matrix by a constant value. double
elementMax()
Returns the maximum value among all elements in the matrix. double
elementMaxAbs()
Returns the maximum absolute value among all elements in the matrix. double
elementMin()
Returns the minimum value among all elements in the matrix. Matrix
elementMult(Matrix B)
Performs in-place element-wise multiplication with another matrix. Matrix
elementMult(Matrix B, Matrix output)
Performs element-wise multiplication with another matrix, storing the result in the given output matrix. double
elementMult()
Computes the product of the elements of a row or column vector. Matrix
elementMultWithVector(Matrix B)
Performs element-wise multiplication between this matrix and a row vector. Matrix
elementPow(double a)
Raises each non-zero element of the matrix to the specified power. Matrix
elementPower(double t)
Raises each element of the matrix to the given power. double
elementSum()
Computes the sum of all elements in the matrix. boolean
equals(Object obj)
Checks for matrix equality. Matrix
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
expandMatrixToSquare()
Expands the matrix to be square, padding with zeros as needed. Matrix
fact()
Computes the factorial of each element in the matrix. Matrix
factln()
Computes the natural logarithm of the factorial for each element. Matrix
fill(double val)
Fills all entries in the matrix with the given value. Matrix
find()
Returns the linear indices of all non-zero elements in the matrix. Matrix
findNonNegative()
Returns the linear indices of all elements that are non-negative (≥ 0). List<Integer>
findNonZeroRowsInColumn(int column)
Finds all row indices in a given column where the value is non-zero. Matrix
findNumber(double number)
Finds all linear indices where the matrix has a specific value. Matrix
findZero()
Finds all linear indices where the matrix value is zero. Matrix
fromArray2D(Array<Array<int>> matrix)
Populates the matrix from a 2D integer array. Matrix
fromArray2D(Array<Array<double>> matrix)
Populates the matrix from a 2D double array. double
get(int i, int j)
Returns the value at the specified row and column. double
get(int idx)
Returns the value at the specified index. Array<int>
getColIndexes()
Returns internal column index array from the sparse matrix structure. int
getColMax(int col)
Returns the row index of the maximum value in the specified column. Matrix
getColumn(int j)
Returns a column of the matrix as a new single-column matrix. ColumnView
getColumnView(int j)
Returns a lightweight view into the specified column without copying data. DMatrix
getData()
void
setData(DMatrix newData)
Array<int>
getNonZeroCols()
Returns an array of unique column indices containing non-zero elements. int
getNonZeroLength()
Returns the number of non-zero values in the matrix. Array<int>
getNonZeroRows()
Returns array of row indices of non-zero entries. Array<double>
getNonZeroValues()
Returns array of non-zero values in the matrix. int
getNonZeros()
Returns the number of non-zero elements in this matrix. int
getNumCols()
Returns the number of columns in this matrix. int
getNumElements()
Returns total number of elements in the matrix. int
getNumNonZeros()
int
getNumRows()
Returns the number of rows in this matrix. 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. RowView
getRowView(int i)
Returns a lightweight view into the specified row without copying data. Matrix
getRowsFrom(int row)
Returns a new matrix consisting of rows from the given start index to the end. Matrix
getSlice(int r0, int r1, int c0, int c1)
Extracts a submatrix based on row/column bounds. Matrix
getSlice(Array<boolean> rowFlags, Array<boolean> colFlags)
Extracts a submatrix from rows/columns marked as true in input flags. Matrix
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. Matrix
hadamard(Matrix B)
Performs the Hadamard (element-wise) product of two matrices. boolean
hasDuplicates()
boolean
hasFinite()
boolean
hasInfinite()
boolean
hasMultipleFinite()
boolean
hasNaN()
int
hashCode()
Generates a hash code for the matrix based on its values. 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. Matrix
inv()
Computes the inverse of the matrix. boolean
isAssigned(int row, int col)
Checks whether a specific element is assigned in the sparse matrix. boolean
isDiag()
Determines whether the matrix is a diagonal matrix. boolean
isEmpty()
Checks if the matrix is empty (has zero rows or columns). boolean
isEqualTo(Matrix m)
Checks if two matrices are exactly equal. boolean
isEqualToTol(Matrix m, double tol)
Checks if two matrices are equal within a specified tolerance. boolean
isFinite()
Checks whether all matrix elements are finite. boolean
isInteger()
Checks if all values in the matrix are integers. void
keepCols(Collection<Integer> cols)
Keeps only the specified columns in the matrix. void
keepRows(Collection<Integer> rows)
Keeps only the specified rows in the matrix. Matrix
kron(Matrix b)
Computes the Kronecker product of this matrix and another matrix. Matrix
krons(Matrix other)
Computes the Kronecker sum of two matrices: A ⊕ B = A ⊗ I + I ⊗ B, where ⊗ is the Kronecker product and I is the identity matrix of matching size. Matrix
leftMatrixDivide(Matrix b)
Solves the equation AX = B for X, where A is this matrix and B is the right-hand side. int
length()
Returns the length of the matrix, defined as max(rows, cols). Matrix
log()
Applies the natural logarithm element-wise. Matrix
meanCol()
Computes the mean of each column. Matrix
meanRow()
Computes the mean of each row. void
mulByMinusOne()
Multiplies all elements in the matrix by -1 in-place. Matrix
mult(Matrix B)
Performs matrix multiplication: this * B Matrix
mult(Matrix B, Matrix out)
Performs matrix multiplication: this * B double
multColumnView(ColumnView columnView)
Efficiently multiplies this row vector with a column view. void
multEq(Matrix B)
Replaces this matrix with the result of this * B. double
multRowView(RowView rowView)
Efficiently multiplies a row view with this column vector. double
norm()
Computes the Euclidean norm of a matrix void
ones()
Fills the matrix with ones. 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
prettyPrint()
Pretty prints the matrix with automatic formatting and alignment. void
prettyPrintInt()
Pretty prints the matrix assuming integer values. void
print()
Prints the matrix with appropriate formatting, either as floats or integers. void
printNonZero()
Prints only non-zero values and their positions in the matrix. Map<String, Matrix>
qr()
Performs QR decomposition on the matrix. void
randMatrix(int length)
Fills the matrix with random values between 0 and 1. int
rank()
Computes the rank of the matrix. Matrix
reciprocal()
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
removeCols(Collection<Integer> cols)
Removes the specified columns from the matrix. void
removeInfinite()
Replaces all infinite values (positive or negative) in the matrix with 0. void
removeInfinity()
Removes all infinite values (positive or negative) from the sparse matrix structure. void
removeNaN()
Removes all NaN values from the matrix structure. void
removeNegative()
Removes all negative values from the matrix structure. void
removeRows(Collection<Integer> rows)
Removes the specified rows from the matrix. 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. 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. Matrix
reverse()
Reverses the elements of a vector (row or column) matrix. Matrix
reverseRows()
Reverses the order of rows in the matrix. Matrix
rightMatrixDivide(Matrix b)
Performs right matrix division A / B = A * inv(B) void
rowIncrease(int row, double a)
Increases all elements in the specified row by a scalar value. Matrix
safeMult(Matrix B)
Matrix
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. Map<String, Matrix>
schur(String method, Integer iter)
Computes the Schur decomposition of the matrix. Map<String, Matrix>
schur()
Computes the Schur decomposition with the default method and iteration count. 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. Matrix
setColumn(int j, Matrix col)
Sets the specified column to the values in the given vector. Matrix
setColumns(int j0, int j1, Matrix cols)
Sets multiple columns starting from column index j0 to j1 (exclusive) using values from another matrix. void
setNaNTo(double val)
Replaces all NaN entries in the matrix with the specified value. void
setNaNToZero()
Replaces all NaN entries in the matrix with zero. Matrix
setRow(int j, Matrix row)
Sets the specified row to the values in the given vector. Matrix
setRows(int i0, int i1, Matrix rows)
Sets multiple rows starting from row index i0 to i1 (exclusive) using values from another matrix. 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
setTo(Matrix m)
Copies the data from another matrix into this matrix. void
setToNaN()
Sets all elements of the matrix to NaN. void
shrinkNumCols(int newmax)
void
shrinkNumRows(int newmax)
Matrix
sort()
Returns a new matrix with the non-zero values sorted in ascending order. Matrix
sortEq()
Sorts the current matrix's non-zero values in place. Matrix
sqrt()
Computes the element-wise square root of the matrix. Matrix
square()
Computes the matrix multiplied by itself. Matrix
sub(double x)
Subtract a scalar from all elements. Matrix
sub(Matrix matrix)
Subtracts another matrix. Matrix
sub(double alpha, Matrix matrix)
Subtracts alpha-scaled version of the provided matrix. void
subEq(double x)
Subtracts a scalar from the current matrix in place. void
subEq(Matrix matrix)
Subtracts a matrix from the current matrix in place. void
subEq(double alpha, Matrix matrix)
Subtracts a scaled 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. double
sumCols(int col)
Sums the elements in the specified column. Matrix
sumCols()
Sums the values in each column and returns the results as a row vector. Matrix
sumCols(int startRow, int endRow)
Computes the sum of a subset of rows for each column. double
sumRows(int row)
Computes the sum of the values in a specific row. Matrix
sumRows()
Computes the sum of each row and returns the result as a column vector. Matrix
sumRows(int startCol, int endCol)
Computes the sum over a subrange of columns for each row. double
sumSubMatrix(int startRow, int endRow, int startCol, int endCol)
Computes the sum of the values in a rectangular submatrix. double
sumSubMatrix(Array<int> rowIndexes, Array<int> colIndexes)
Computes the sum of a submatrix defined by specific row and column indices. double
sumSubMatrix(Array<boolean> rowIndexes, Array<boolean> colIndexes)
Computes the sum of a submatrix defined by boolean selection flags. Array<double>
toArray1D()
Converts the matrix to a flat 1D array in row-major order. Array<Array<double>>
toArray2D()
Converts the matrix to a 2D array representation. DMatrixSparseCSC
toDMatrixSparseCSC()
Converts this matrix to a copy of its underlying DMatrixSparseCSC structure. DMatrixSparseCSC
toDMatrixSparseCSC(Matrix matrix)
Converts a specified matrix to a copy of its underlying DMatrixSparseCSC structure. Double
toDouble()
Converts this matrix to a single Double
value.List<List<Double>>
toDoubleList()
Converts the matrix to a nested list of Double
values.Array<int>
toIntArray1D()
Converts the matrix to a 1D array of int
, flattening in row-major order.List<Double>
toList1D()
Converts the matrix into a 1D List of Double
values in row-major order.String
toString()
Returns a formatted string representation of the matrix. Matrix
transpose()
Computes the transpose of the current matrix. Matrix
uniqueInCol(int colIdx)
Finds unique integer values in the specified column of the matrix. Matrix
uniqueInRow(int rowIdx)
Finds unique integer values in the specified row of the matrix. Matrix
uniqueNonNegativeInCol(int colIdx)
Finds unique positive values (strictly greater than 0) in the specified column. Matrix
uniqueNonNegativeInRow(int rowIdx)
Finds unique positive values (strictly greater than 0) in the specified row. Matrix
uniqueNonZerosInCol(int colIdx)
Finds unique non-zero values in the specified column. Matrix
uniqueNonZerosInRow(int rowIdx)
Finds unique non-zero values in the specified row. void
unsafeSet(int row, int col, double val)
Sets a value in the matrix without bounds checking. double
value()
Returns the value at position (0, 0). void
zero()
Sets all entries in the matrix to zero. -
-
Constructor Detail
-
Matrix
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
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
Matrix(Matrix matrix)
Creates a copy of the specified matrix.- Parameters:
matrix
- the matrix to copy
-
Matrix
Matrix(DMatrix matrix)
Creates a matrix from an EJML DMatrix (sparse).- Parameters:
matrix
- the EJML sparse matrix to wrap
-
Matrix
Matrix(DMatrixRMaj matrix)
Creates a matrix from an EJML DMatrixRMaj (dense).- Parameters:
matrix
- the EJML dense matrix to wrap
-
Matrix
Matrix(Array<Array<double>> arrays)
Creates a matrix from a 2D double array.- Parameters:
arrays
- 2D array containing the matrix elements
-
Matrix
Matrix(Array<Array<Double>> arrays)
Creates a matrix from a Kotlin Arraytype.- Parameters:
arrays
- Kotlin Array containing DoubleArray rows
-
Matrix
Matrix(Array<int> array)
Creates a column vector from an integer array.- Parameters:
array
- integer array to convert to column vector
-
Matrix
Matrix(Array<double> array)
Creates a column vector from a double array.- Parameters:
array
- double array to convert to column vector
-
Matrix
Matrix(SimpleMatrix matrix)
-
Matrix
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.
-
-
Method Detail
-
allbut
static Matrix allbut(Matrix y, int k)
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
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
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 matrixmatrixB
- second input matrix
-
cell2mat
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
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
-
columnMatrixToDoubleArray
static Array<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
-
compare
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 matrixB
- The second matrixop
- The comparison operator as a string- Returns:
true if the comparison holds for all elements, false otherwise
-
concatColumns
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 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
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 topbottom
- The matrix to appear belowout
- (Optional) Output matrix to store the result; can be null- Returns:
A matrix representing [top; bottom]
-
createLike
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
-
diag
static Matrix diag(Array<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
static Matrix diagMatrix(Array<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
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
static Matrix diagMatrix(Matrix A, Array<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 matrixA
is 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 invalues
to read fromlength
- The number of values to place on the diagonal- Returns:
A matrix with
values[offset + i]
placed at position (i, i)
-
elementMinNonZero
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
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 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 indst
dstX0
- Starting column index indst
-
extract
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 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
static Matrix extractColumn(Matrix A, int column, Matrix out)
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
static Matrix extractColumns(Matrix A, int col0, int col1)
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
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 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
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 matrixoutputB
- The matrix to store the diagonal values
-
extractRows
static Matrix extractRows(Matrix A, int row0, int row1)
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
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 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
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
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
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 checkisRow
- If true, checks rows; if false, checks columns- Returns:
A list of indices corresponding to zero-sum rows or columns
-
findRows
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 searchrow
- A 1-row matrix to compare against- Returns:
A list of row indices in
matrix
that matchrow
-
firstNorm
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
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
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 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
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
-
intersect
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 matrixmatrixB
- Second input matrix- Returns:
A list of values common to both matrices
-
inv
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
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
-
logsumexp
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₂, ...- Returns:
The log-sum-exp of the input values
-
lyap
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 assuming it implements the solver.
- Parameters:
A
- The matrix AB
- IgnoredC
- The matrix QD
- Ignored- Returns:
The solution matrix X
-
matchrow
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 searchrow
- A single-row matrix to match- Returns:
The index of the matching row, or -1 if no match is found
-
matrixAddVector
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 matrixvector
- A column vector (adds to each row) or a row vector (adds to each column)- Returns:
A new matrix with the vector added
-
maxAbsDiff
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 matrixb
- Second matrix (denominator for relative difference)- Returns:
The maximum relative absolute difference
-
negative
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
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
static Matrix oner(Matrix N, Integer s)
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
s
decreased by one, if in bounds
-
oner
static Matrix oner(Matrix N, List<Integer> r)
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
r
decreased by one
-
ones
static Matrix ones(int rows, int cols)
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
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 matrixb
- The exponent (must be ≥ 0)- Returns:
The matrix
a
raised to the powerb
-
readFromFile
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
-
removeRows
static Array<Array<Array<double>>> removeRows(Array<Array<Array<double>>> array, Matrix rowsToRemove)
-
removeTrailingNewLine
static String removeTrailingNewLine(String str)
-
scaleMult
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 matrixn
- The scalar multiplier- Returns:
A new matrix equal to
a * n
-
singleton
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
static boolean solve(Matrix a, Matrix b, Matrix x)
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
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 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
-
spectd
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
-
sumCumprod
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
-
sylv
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 matrixB
- Right coefficient matrixC
- Constant matrix- Returns:
Solution matrix X
-
tril
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
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 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
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 matrixB
- The matrix whose non-zero entries override A- Returns:
A matrix representing the union of A and B
-
uniqueRowIndexes
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
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.
- Parameters:
m
- The input matrixstartCol
- 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
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.
- 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
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 matrixcolsToIgnore
- Indexes to be ignored- Returns:
A set of sets, each representing a weakly connected component
-
zeros
static Matrix zeros(int rows, int cols)
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
void absEq()
-
add
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
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
Matrix add(double alpha, Matrix matrix)
Adds
alpha * matrix
to this matrix.- Parameters:
alpha
- The scalar multipliermatrix
- The matrix to add- Returns:
A new matrix containing the result
-
addEq
void addEq(double alpha)
Adds a scalar value to each element of the matrix in-place.
- Parameters:
alpha
- The scalar value to add
-
addEq
void addEq(Matrix matrix)
Adds another matrix to this matrix in-place:
this += matrix
.- Parameters:
matrix
- The matrix to add
-
addEq
void addEq(double alpha, Matrix matrix)
Adds
alpha * matrix
to this matrix in-place:this += alpha * matrix
.- Parameters:
alpha
- The scalar multipliermatrix
- The matrix to add
-
allEqualToOne
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
boolean any()
-
apply
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
andop
, 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
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
Matrix ceilEq()
Applies the ceiling operation in-place to each element of this matrix.
- Returns:
This matrix after applying ceiling element-wise.
-
changeSign
void changeSign()
Negates all values in the matrix, in-place.
-
copy
Matrix copy()
Returns a deep copy of this matrix.
- Returns:
A cloned matrix identical to this one.
-
colIncrease
void colIncrease(int col, double a)
-
colon
Matrix colon()
Returns the matrix in column-major order.
- Returns:
The same matrix interpreted in column-major order.
-
columnMajorOrder
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
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
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
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
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
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
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.- Returns:
A new block diagonal matrix combining this and matrix2.
-
cumsumViaCol
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
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
double det()
Computes the determinant of the matrix.
- Returns:
Determinant value.
-
div
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
void divEq(Matrix den)
Performs in-place element-wise division between this matrix and the provided matrix.
- Parameters:
den
- The denominator matrix.
-
divide
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
void divideEq(double scalar)
Performs in-place division of this matrix by a scalar.
- Parameters:
scalar
- The scalar divisor.
-
divideRows
void divideRows(Array<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
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.
-
eigvec
Ret.Eigs eigvec()
Computes the eigenvalues and eigenvectors of this square matrix.
- Returns:
A Ret.Eigs object containing the eigenvalues and eigenvectors.
-
expm_higham
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
-
norm1
double norm1()
Computes the 1-norm of the matrix (maximum absolute column sum).
- Returns:
The 1-norm of the matrix
-
elementDiv
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.
-
elementDivide
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
-
elementIncrease
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
double elementMax()
Returns the maximum value among all elements in the matrix.
- Returns:
maximum element value
-
elementMaxAbs
double elementMaxAbs()
Returns the maximum absolute value among all elements in the matrix.
- Returns:
maximum absolute element value
-
elementMin
double elementMin()
Returns the minimum value among all elements in the matrix.
- Returns:
minimum element value
-
elementMult
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
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 withoutput
- the matrix to store the result in (if null, a new matrix is created)- Returns:
the result of the element-wise multiplication
-
elementMult
double elementMult()
Computes the product of the elements of a row or column vector.
- Returns:
the product of all elements
-
elementMultWithVector
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
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
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
double elementSum()
Computes the sum of all elements in the matrix.
- Returns:
the sum of all elements
-
equals
boolean equals(Object obj)
Checks for matrix equality.
- Parameters:
obj
- the object to compare with- Returns:
true if matrices are equal, false otherwise
-
exp
Matrix exp()
Applies the exponential function to each element of the matrix.
- Returns:
a new matrix with exponentiated elements
-
expandMatrix
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
void expandMatrixToSquare()
Expands the matrix to be square, padding with zeros as needed.
-
fact
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
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
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
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
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
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
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
Matrix findZero()
Finds all linear indices where the matrix value is zero.
- Returns:
a matrix containing the linear indices of zero-valued elements
-
fromArray2D
Matrix fromArray2D(Array<Array<int>> matrix)
Populates the matrix from a 2D integer array.
- Parameters:
matrix
- 2D array of integers- Returns:
this matrix after population
-
fromArray2D
Matrix fromArray2D(Array<Array<double>> matrix)
Populates the matrix from a 2D double array.
- Parameters:
matrix
- 2D array of doubles- Returns:
this matrix after population
-
get
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
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
Array<int> getColIndexes()
Returns internal column index array from the sparse matrix structure.
- Returns:
array of column indexes
-
getColMax
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
Matrix getColumn(int j)
Returns a column of the matrix as a new single-column matrix.
- Parameters:
j
- column index- Returns:
column matrix
-
getColumnView
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
DMatrix getData()
-
setData
void setData(DMatrix newData)
-
getNonZeroCols
Array<int> getNonZeroCols()
Returns an array of unique column indices containing non-zero elements.
- Returns:
array of column indices
-
getNonZeroLength
int getNonZeroLength()
Returns the number of non-zero values in the matrix.
- Returns:
number of non-zero elements
-
getNonZeroRows
Array<int> getNonZeroRows()
Returns array of row indices of non-zero entries.
- Returns:
array of row indices
-
getNonZeroValues
Array<double> getNonZeroValues()
Returns array of non-zero values in the matrix.
- Returns:
array of non-zero values
-
getNonZeros
int getNonZeros()
Returns the number of non-zero elements in this matrix.
- Returns:
the number of non-zero elements
-
getNumCols
int getNumCols()
Returns the number of columns in this matrix.
- Returns:
the number of columns
-
getNumElements
int getNumElements()
Returns total number of elements in the matrix.
- Returns:
total element count
-
getNumNonZeros
int getNumNonZeros()
-
getNumRows
int getNumRows()
Returns the number of rows in this matrix.
- Returns:
the number of rows
-
getRow
Matrix getRow(int i)
Returns the specified row as a single-row matrix.
- Parameters:
i
- row index- Returns:
row matrix
-
getRowMax
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
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
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
Matrix getSlice(int r0, int r1, int c0, int c1)
Extracts a submatrix based on row/column bounds.
- Parameters:
r0
- start rowr1
- end row (exclusive)c0
- start columnc1
- end column (exclusive)- Returns:
submatrix
-
getSlice
Matrix getSlice(Array<boolean> rowFlags, Array<boolean> colFlags)
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
Matrix getSubMatrix(Matrix rows, Matrix cols)
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
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
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
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
boolean hasDuplicates()
-
hasFinite
boolean hasFinite()
-
hasInfinite
boolean hasInfinite()
-
hasMultipleFinite
boolean hasMultipleFinite()
-
hasNaN
boolean hasNaN()
-
hashCode
int hashCode()
Generates a hash code for the matrix based on its values.
- Returns:
hash code
-
insertSubMatrix
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
-
isAssigned
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
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
boolean isEmpty()
Checks if the matrix is empty (has zero rows or columns).
- Returns:
true if empty, false otherwise
-
isEqualTo
boolean isEqualTo(Matrix m)
Checks if two matrices are exactly equal.
- Parameters:
m
- the matrix to compare- Returns:
true if equal, false otherwise
-
isEqualToTol
boolean isEqualToTol(Matrix m, double tol)
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
boolean isFinite()
Checks whether all matrix elements are finite.
- Returns:
true if all elements are finite, false otherwise
-
isInteger
boolean isInteger()
Checks if all values in the matrix are integers.
- Returns:
true if all values are integers, false otherwise
-
keepCols
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
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
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
Matrix krons(Matrix other)
Computes the Kronecker sum of two matrices: A ⊕ B = A ⊗ I + I ⊗ B, where ⊗ 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
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
int length()
Returns the length of the matrix, defined as max(rows, cols).
- Returns:
The maximum dimension of the matrix
-
log
Matrix log()
Applies the natural logarithm element-wise.
- Returns:
A new matrix with log applied to each element
-
meanCol
Matrix meanCol()
Computes the mean of each column.
- Returns:
A 1xN matrix containing the mean of each column
-
meanRow
Matrix meanRow()
Computes the mean of each row.
- Returns:
An Nx1 matrix containing the mean of each row
-
mulByMinusOne
void mulByMinusOne()
Multiplies all elements in the matrix by -1 in-place.
-
mult
Matrix mult(Matrix B)
Performs matrix multiplication: this * B
- Parameters:
B
- The right-hand side matrix- Returns:
Resultant matrix
-
mult
Matrix mult(Matrix B, Matrix out)
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
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
-
multEq
void multEq(Matrix B)
Replaces this matrix with the result of this * B.
- Parameters:
B
- The right-hand side matrix
-
multRowView
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
-
norm
double norm()
Computes the Euclidean norm of a matrix
- Returns:
- the Euclidean norm of the given matrix
-
ones
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
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
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
void prettyPrint()
Pretty prints the matrix with automatic formatting and alignment. Supports real, NaN, Inf, and -Inf values.
-
prettyPrintInt
void prettyPrintInt()
Pretty prints the matrix assuming integer values.
-
print
void print()
Prints the matrix with appropriate formatting, either as floats or integers.
-
printNonZero
void printNonZero()
Prints only non-zero values and their positions in the matrix.
-
qr
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
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
int rank()
Computes the rank of the matrix.
- Returns:
The rank of the matrix.
-
reciprocal
Matrix reciprocal()
Computes the element-wise reciprocal (1/x) of the matrix.
- Returns:
A new matrix with reciprocal values.
-
remove
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
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
void removeInfinite()
Replaces all infinite values (positive or negative) in the matrix with 0. Also adjusts internal bookkeeping fields to maintain structural integrity.
-
removeInfinity
void removeInfinity()
Removes all infinite values (positive or negative) from the sparse matrix structure. This shifts remaining values to preserve compactness.
-
removeNaN
void removeNaN()
Removes all NaN values from the matrix structure. Internal arrays are compacted and updated accordingly.
-
removeNegative
void removeNegative()
Removes all negative values from the matrix structure. Shifts non-negative values to preserve compactness.
-
removeRows
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
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
void replace(double delete, double replacement)
Replaces all occurrences of a specific value with a new value in the matrix.
- Parameters:
delete
- the value to be replacedreplacement
- the value to insert in place of the deleted value
-
repmat
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 dimensioncols
- number of times to repeat along the column dimension- Returns:
a new matrix formed by repeating this matrix
-
reshape
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
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
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
Matrix reverseRows()
Reverses the order of rows in the matrix.
- Returns:
a new matrix with rows in reverse order
-
rightMatrixDivide
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
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
-
scale
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
-
scaleEq
void scaleEq(double scalar)
Scales this matrix in-place by the given scalar value.
- Parameters:
scalar
- the value to scale each element by
-
scaleEq
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 multiplieroutput
- the matrix to store the result
-
schur
Map<String, Matrix> schur(String method, Integer iter)
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
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
-
set
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
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
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
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 setcol
- the column vector to copy from- Returns:
this matrix after the operation
-
setColumns
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
void setNaNTo(double val)
Replaces all NaN entries in the matrix with the specified value.
- Parameters:
val
- value to replace NaNs with
-
setNaNToZero
void setNaNToZero()
Replaces all NaN entries in the matrix with zero.
-
setRow
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 setrow
- the row vector to copy from- Returns:
this matrix after the operation
-
setRows
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
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
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
void setTo(Matrix m)
Copies the data from another matrix into this matrix.
- Parameters:
m
- the matrix to copy from
-
setToNaN
void setToNaN()
Sets all elements of the matrix to NaN.
-
shrinkNumCols
void shrinkNumCols(int newmax)
-
shrinkNumRows
void shrinkNumRows(int newmax)
-
sort
Matrix sort()
Returns a new matrix with the non-zero values sorted in ascending order.
- Returns:
a new matrix with sorted values
-
sortEq
Matrix sortEq()
Sorts the current matrix's non-zero values in place.
- Returns:
this matrix after sorting
-
sqrt
Matrix sqrt()
Computes the element-wise square root of the matrix.
- Returns:
the resulting matrix
-
sub
Matrix sub(double x)
Subtract a scalar from all elements.
- Parameters:
x
- the scalar value to subtract- Returns:
the resulting matrix
-
sub
Matrix sub(Matrix matrix)
Subtracts another matrix.
- Parameters:
matrix
- the matrix to subtract- Returns:
the resulting matrix
-
sub
Matrix sub(double alpha, Matrix matrix)
Subtracts alpha-scaled version of the provided matrix.
- Parameters:
alpha
- the scalar multipliermatrix
- the matrix to subtract- Returns:
the resulting matrix
-
subEq
void subEq(double x)
Subtracts a scalar from the current matrix in place.
- Parameters:
x
- the scalar to subtract
-
subEq
void subEq(Matrix matrix)
Subtracts a matrix from the current matrix in place.
- Parameters:
matrix
- the matrix to subtract
-
subEq
void subEq(double alpha, Matrix matrix)
Subtracts a scaled matrix from the current matrix in place.
- Parameters:
alpha
- the scale factormatrix
- the matrix to subtract
-
sumAbsCols
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
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
double sumCols(int col)
Sums the elements in the specified column.
- Parameters:
col
- the column index- Returns:
the sum of the column values
-
sumCols
Matrix sumCols()
Sums the values in each column and returns the results as a row vector.
- Returns:
a row vector with column sums
-
sumCols
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
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
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
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
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
double sumSubMatrix(Array<int> rowIndexes, Array<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
double sumSubMatrix(Array<boolean> rowIndexes, Array<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
Array<double> toArray1D()
Converts the matrix to a flat 1D array in row-major order.
- Returns:
the 1D array representation of the matrix
-
toArray2D
Array<Array<double>> toArray2D()
Converts the matrix to a 2D array representation.
- Returns:
the 2D array representation of the matrix
-
toDMatrixSparseCSC
DMatrixSparseCSC toDMatrixSparseCSC()
Converts this matrix to a copy of its underlying DMatrixSparseCSC structure.
- Returns:
a deep copy of the internal sparse matrix representation
-
toDMatrixSparseCSC
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
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
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
Array<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
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
String toString()
Returns a formatted string representation of the matrix. Each row is separated by a semicolon and new line.
- Returns:
the string representation of the matrix
-
transpose
Matrix transpose()
Computes the transpose of the current matrix.
- Returns:
a new matrix representing the transpose of this matrix
-
uniqueInCol
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
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
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
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
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
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
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
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
void zero()
Sets all entries in the matrix to zero.
-
-
-
-