public final class MatrixUtils extends Object
This class is up-to-date with commons-math 3.6.1.
| Modifier and Type | Field and Description |
|---|---|
static RealMatrixFormat |
DEFAULT_FORMAT
Deprecated.
since 4.5 the denomination has changed to
JAVA_FORMAT |
static RealMatrixFormat |
JAVA_FORMAT
The JAVA format for
RealMatrix objects. |
static RealMatrixFormat |
OCTAVE_FORMAT
A format for
RealMatrix objects compatible with octave. |
static RealMatrixFormat |
SCILAB_FORMAT
The SCILAB format for
RealMatrix objects. |
static RealMatrixFormat |
SUMMARY_FORMAT
Summary visual format for
RealMatrix objects displayed on several rows. |
static RealMatrixFormat |
VISUAL_FORMAT
Visual format for
RealMatrix objects displayed on several rows. |
| Modifier and Type | Method and Description |
|---|---|
static Array2DRowRealMatrix |
bigFractionMatrixToRealMatrix(FieldMatrix<BigFraction> m)
|
static RealMatrix |
blockInverse(RealMatrix m,
int splitIndex)
Computes the inverse of the given matrix by splitting it into
4 sub-matrices.
|
static void |
checkAdditionCompatible(AnyMatrix left,
AnyMatrix right)
Check if matrices are addition compatible.
|
static void |
checkColumnIndex(AnyMatrix m,
int column)
Check if a column index is valid.
|
static void |
checkDimension(int expected,
int actual)
Check if the provided dimension is the one expected.
|
static void |
checkMatrixIndex(AnyMatrix m,
int row,
int column)
Check if matrix indices are valid.
|
static void |
checkMultiplicationCompatible(AnyMatrix left,
AnyMatrix right)
Check if matrices are multiplication compatible
|
static void |
checkMultiplicationCompatible(AnyMatrix left,
AnyMatrix right,
boolean rightToTransposed)
Check if matrices are multiplication compatible
|
static void |
checkPermutationMatrixIndex(AnyMatrix m,
int[] index)
Check if the index array is compatible with the matrix m for permutation.
|
static void |
checkRowIndex(AnyMatrix m,
int row)
Check if a row index is valid.
|
static void |
checkSubMatrixIndex(AnyMatrix m,
int[] selectedRows,
int[] selectedColumns)
Check if submatrix ranges indices are valid.
|
static void |
checkSubMatrixIndex(AnyMatrix m,
int startRow,
int endRow,
int startColumn,
int endColumn)
Check if submatrix ranges indices are valid.
|
static void |
checkSubtractionCompatible(AnyMatrix left,
AnyMatrix right)
Check if matrices are subtraction compatible
|
static void |
checkSymmetric(RealMatrix matrix,
double eps)
Checks whether a matrix is symmetric.
|
static void |
checkSymmetry(RealMatrix matrix,
double absTol,
double relTol)
Check if the matrix is symmetric.
|
static int[] |
completePermutationIndexList(AnyMatrix m,
int[] preFilledIndex)
To make it easier to use the method
SymmetricMatrix.extractSubSymmetricMatrix(int[])
this method automatically
fill a pre-filled index list (preFilledIndex) to process the permutation on a specified matrix (m
) (external process). |
static RealMatrix |
concatenateHorizontally(RealMatrix left,
RealMatrix right)
Concatenates two matrices horizontally.
|
static RealMatrix |
concatenateVertically(RealMatrix upper,
RealMatrix lower)
Concatenates two matrices vertically.
|
static <T extends FieldElement<T>> |
createColumnFieldMatrix(T[] columnData)
Creates a column
FieldMatrix using the data from the input
array. |
static RealMatrix |
createColumnRealMatrix(double[] columnData)
Creates a column
RealMatrix using the data from the input
array. |
static <T extends FieldElement<T>> |
createFieldDiagonalMatrix(T[] diagonal)
Returns a diagonal matrix with specified elements.
|
static <T extends FieldElement<T>> |
createFieldIdentityMatrix(Field<T> field,
int dimension)
Returns
dimension x dimension identity matrix. |
static <T extends FieldElement<T>> |
createFieldMatrix(Field<T> field,
int rows,
int columns)
Returns a
FieldMatrix with specified dimensions. |
static <T extends FieldElement<T>> |
createFieldMatrix(T[][] data)
Returns a
FieldMatrix whose entries are the the values in the
the input array. |
static <T extends FieldElement<T>> |
createFieldVector(T[] data)
Creates a
FieldVector using the data from the input array. |
static RealMatrix |
createRealDiagonalMatrix(double[] diagonal)
Returns a diagonal matrix with specified elements.
|
static RealMatrix |
createRealIdentityMatrix(int dimension)
Returns
dimension x dimension identity matrix. |
static RealMatrix |
createRealIdentityMatrix(int dimension,
boolean returnDiagonalMatrix)
Returns
dimension x dimension identity matrix. |
static RealMatrix |
createRealMatrix(double[][] data)
Returns a
RealMatrix whose entries are the the values in the
the input array. |
static RealMatrix |
createRealMatrix(double[][] data,
boolean forceCopyArray)
Returns a
RealMatrix whose entries are the the values in the
the input array. |
static RealMatrix |
createRealMatrix(int rows,
int columns)
Returns a
RealMatrix with specified dimensions. |
static RealVector |
createRealVector(double[] data)
Creates a
RealVector using the data from the input array. |
static <T extends FieldElement<T>> |
createRowFieldMatrix(T[] rowData)
Create a row
FieldMatrix using the data from the input
array. |
static RealMatrix |
createRowRealMatrix(double[] rowData)
Create a row
RealMatrix using the data from the input
array. |
static void |
deserializeRealMatrix(Object instance,
String fieldName,
ObjectInputStream ois)
Deserialize a
RealMatrix field in a class. |
static void |
deserializeRealVector(Object instance,
String fieldName,
ObjectInputStream ois)
Deserialize a
RealVector field in a class. |
static Array2DRowRealMatrix |
fractionMatrixToRealMatrix(FieldMatrix<Fraction> m)
|
static RealMatrix |
multiplyByTranspose(double alpha,
RealMatrix matrixL,
RealMatrix matrixR)
Multiplies the matrix L by RT and by a scalar factor α.
|
static RealMatrix |
multiplyByTranspose(RealMatrix matrixL,
RealMatrix matrixR)
Multiplies the matrix L by RT.
|
static RealMatrix |
resize(RealMatrix matrix,
int rowDim,
int colDim)
Resizes the provided matrix to a NxM matrix.
|
static void |
serializeRealMatrix(RealMatrix matrix,
ObjectOutputStream oos)
Serialize a
RealMatrix. |
static void |
serializeRealVector(RealVector vector,
ObjectOutputStream oos)
Serialize a
RealVector. |
static void |
solveLowerTriangularSystem(RealMatrix rm,
RealVector b)
Solve a system of composed of a Lower Triangular Matrix
RealMatrix. |
static void |
solveUpperTriangularSystem(RealMatrix rm,
RealVector b)
Solver a system composed of an Upper Triangular Matrix
RealMatrix. |
@Deprecated public static final RealMatrixFormat DEFAULT_FORMAT
JAVA_FORMATRealMatrix objects.public static final RealMatrixFormat JAVA_FORMAT
RealMatrix objects.public static final RealMatrixFormat OCTAVE_FORMAT
RealMatrix objects compatible with octave.public static final RealMatrixFormat SCILAB_FORMAT
RealMatrix objects.public static final RealMatrixFormat VISUAL_FORMAT
RealMatrix objects displayed on several rows.
The pattern "% 11.5g" by default set the significant digit accuracy at 5, the width equal to 11,
the format is automatically set to digital or scientific and the space between % and 11 allows to display the
sign for scientific values.public static final RealMatrixFormat SUMMARY_FORMAT
RealMatrix objects displayed on several rows.
The pattern "% 11.5g" by default set the significant digit accuracy at 5, the width equal to 11,
the format is automatically set to digital or scientific and the space between % and 11 allows to display the
sign for scientific values.
The summary mode, with an index set to 3, will display the 3x3 sub-matrix in each corner and the rows and columns
total number.public static RealMatrix createRealMatrix(int rows, int columns)
RealMatrix with specified dimensions.
The type of matrix returned depends on the dimension. Below 212 elements (i.e. 4096 elements or
64×64 for a square matrix) which can be stored in a 32kB array, a Array2DRowRealMatrix instance is
built. Above this threshold a BlockRealMatrix instance is built.
The matrix elements are all set to 0.0.
rows - number of rows of the matrixcolumns - number of columns of the matrixcreateRealMatrix(double[][])public static <T extends FieldElement<T>> FieldMatrix<T> createFieldMatrix(Field<T> field, int rows, int columns)
FieldMatrix with specified dimensions.
The type of matrix returned depends on the dimension. Below 212 elements (i.e. 4096 elements or
64×64 for a square matrix), a FieldMatrix instance is built. Above this threshold a
BlockFieldMatrix instance is built.
The matrix elements are all set to field.getZero().
T - the type of the field elementsfield - field to which the matrix elements belongrows - number of rows of the matrixcolumns - number of columns of the matrixcreateFieldMatrix(FieldElement[][])public static RealMatrix createRealMatrix(double[][] data)
RealMatrix whose entries are the the values in the
the input array.
The type of matrix returned depends on the dimension. Below 212 elements (i.e. 4096 elements or
64×64 for a square matrix) which can be stored in a 32kB array, a Array2DRowRealMatrix instance is
built. Above this threshold a BlockRealMatrix instance is built.
The input array is copied, not referenced.
data - input arrayDimensionMismatchException - if data is not rectangular (not all rows have the same length).NoDataException - if a row or column is empty.NullArgumentException - if either data or data[0] is null.DimensionMismatchException - if data is not rectangular.createRealMatrix(int, int)public static RealMatrix createRealMatrix(double[][] data, boolean forceCopyArray)
RealMatrix whose entries are the the values in the
the input array.
The type of matrix returned depends on the dimension. Below 212 elements (i.e. 4096 elements or
64×64 for a square matrix) which can be stored in a 32kB array, a Array2DRowRealMatrix instance is
built. Above this threshold a BlockRealMatrix instance is built.
The input array is copied, not referenced.
data - input arrayforceCopyArray - if true the input array is copied, else it is referenced.DimensionMismatchException - if data is not rectangular (not all rows have the same length).NoDataException - if a row or column is empty.NullArgumentException - if either data or data[0] is null.DimensionMismatchException - if data is not rectangular.createRealMatrix(int, int)public static <T extends FieldElement<T>> FieldMatrix<T> createFieldMatrix(T[][] data)
FieldMatrix whose entries are the the values in the
the input array.
The type of matrix returned depends on the dimension. Below 212 elements (i.e. 4096 elements or
64×64 for a square matrix), a FieldMatrix instance is built. Above this threshold a
BlockFieldMatrix instance is built.
The input array is copied, not referenced.
T - the type of the field elementsdata - input arrayDimensionMismatchException - if data is not rectangular (not all rows have the same length).NoDataException - if a row or column is empty.NullArgumentException - if either data or data[0] is null.createFieldMatrix(Field, int, int)public static RealMatrix createRealIdentityMatrix(int dimension)
dimension x dimension identity matrix.dimension - dimension of identity matrix to generateIllegalArgumentException - if dimension is not positivepublic static RealMatrix createRealIdentityMatrix(int dimension, boolean returnDiagonalMatrix)
dimension x dimension identity matrix.dimension - dimension of identity matrix to generatereturnDiagonalMatrix - boolean indicator, if true a diagonal matrix will be returned, else a complete identity matrix will be
returnedIllegalArgumentException - if dimension is not positivepublic static <T extends FieldElement<T>> FieldMatrix<T> createFieldIdentityMatrix(Field<T> field, int dimension)
dimension x dimension identity matrix.T - the type of the field elementsfield - field to which the elements belongdimension - dimension of identity matrix to generateIllegalArgumentException - if dimension is not positivepublic static RealMatrix createRealDiagonalMatrix(double[] diagonal)
diagonal - diagonal elements of the matrix (the array elements
will be copied)public static <T extends FieldElement<T>> FieldMatrix<T> createFieldDiagonalMatrix(T[] diagonal)
T - the type of the field elementsdiagonal - diagonal elements of the matrix (the array elements
will be copied)public static RealVector createRealVector(double[] data)
RealVector using the data from the input array.data - the input dataNoDataException - if data is empty.NullArgumentException - if data is null.public static <T extends FieldElement<T>> FieldVector<T> createFieldVector(T[] data)
FieldVector using the data from the input array.T - the type of the field elementsdata - the input dataNoDataException - if data is empty.NullArgumentException - if data is null.ZeroException - if data has 0 elementspublic static RealMatrix createRowRealMatrix(double[] rowData)
RealMatrix using the data from the input
array.rowData - the input row dataNoDataException - if rowData is empty.NullArgumentException - if rowData is null.public static <T extends FieldElement<T>> FieldMatrix<T> createRowFieldMatrix(T[] rowData)
FieldMatrix using the data from the input
array.T - the type of the field elementsrowData - the input row dataNoDataException - if rowData is empty.NullArgumentException - if rowData is null.public static RealMatrix createColumnRealMatrix(double[] columnData)
RealMatrix using the data from the input
array.columnData - the input column dataNoDataException - if columnData is empty.NullArgumentException - if columnData is null.public static <T extends FieldElement<T>> FieldMatrix<T> createColumnFieldMatrix(T[] columnData)
FieldMatrix using the data from the input
array.T - the type of the field elementscolumnData - the input column dataNoDataException - if data is empty.NullArgumentException - if columnData is null.public static RealMatrix concatenateHorizontally(RealMatrix left, RealMatrix right)
left - the left matrix [NxM]right - the right matrix [NxL]DimensionMismatchException - if the two matrices don't have the same number of rowspublic static RealMatrix concatenateVertically(RealMatrix upper, RealMatrix lower)
upper - the upper matrix [MxN]lower - the upper matrix [LxN]DimensionMismatchException - if the two matrices don't have the same number of columnspublic static RealMatrix resize(RealMatrix matrix, int rowDim, int colDim)
The provided matrix is truncated or extended, depending on whether its dimensions are bigger or smaller than the requested dimensions. If extended, the terms added are set to zero.
matrix - the matrix to be truncatedrowDim - the row dimension N of the matrix returnedcolDim - the column dimension M of the matrix returnedpublic static RealMatrix multiplyByTranspose(RealMatrix matrixL, RealMatrix matrixR)
This methods allows to combine matrix multiplication and matrix transposition for optimization purposes.
matrixL - the left-side matrix LmatrixR - the right-side matrix R (not its transpose)public static RealMatrix multiplyByTranspose(double alpha, RealMatrix matrixL, RealMatrix matrixR)
This methods allows to combine scalar multiplication, matrix multiplication and matrix transposition for optimization purposes.
alpha - the scalar factor αmatrixL - the left-side matrix LmatrixR - the right-side matrix R (not its transpose)public static void checkSymmetric(RealMatrix matrix, double eps)
matrix - Matrix to check.eps - Relative tolerance.NonSquareMatrixException - if the matrix is not square.NonSymmetricMatrixException - if the matrix is not symmetric.public static void checkMatrixIndex(AnyMatrix m, int row, int column)
m - Matrix.row - Row index to check.column - Column index to check.OutOfRangeException - if row or column is not
a valid index.public static void checkRowIndex(AnyMatrix m, int row)
m - Matrix.row - Row index to check.OutOfRangeException - if row is not a valid index.public static void checkColumnIndex(AnyMatrix m, int column)
m - Matrix.column - Column index to check.OutOfRangeException - if column is not a valid index.public static void checkSubMatrixIndex(AnyMatrix m, int startRow, int endRow, int startColumn, int endColumn)
n - 1.m - Matrix.startRow - Initial row index.endRow - Final row index.startColumn - Initial column index.endColumn - Final column index.OutOfRangeException - if the indices are invalid.NumberIsTooSmallException - if endRow < startRow or endColumn < startColumn.public static void checkSubMatrixIndex(AnyMatrix m, int[] selectedRows, int[] selectedColumns)
m - Matrix.selectedRows - Array of row indices.selectedColumns - Array of column indices.NullArgumentException - if selectedRows or selectedColumns are null.NoDataException - if the row or column selections are empty (zero
length).OutOfRangeException - if row or column selections are not valid.public static void checkSymmetry(RealMatrix matrix, double absTol, double relTol)
matrix - MatrixabsTol - Absolute thresholdrelTol - Relative thresholdPatriusException - if the matrix isn't symmetricpublic static int[] completePermutationIndexList(AnyMatrix m, int[] preFilledIndex)
SymmetricMatrix.extractSubSymmetricMatrix(int[])
this method automatically
fill a pre-filled index list (preFilledIndex) to process the permutation on a specified matrix (m
) (external process).
Requirements :
m needs to be square.Usage example : We want to rearrange the rows/colums {2, 3} on a 5x5 matrix but we don't care about the others. Thanks to this method, the full-filled index list will be automatically build as {2, 3, 0, 1, 4}.
Note : To fill the index list, the order is conservative when an index isn't specified.
m - The matrix to complete the index list on (only used for its dimensions)preFilledIndex - The pre-filled index listpublic static void checkPermutationMatrixIndex(AnyMatrix m, int[] index)
m - Matrix.index - index list.NonSquareMatrixException - if m isn't square.NullArgumentException - if index is null.DimensionMismatchException - if index dimension is larger than matrix dimensionNoDataException - if the row or column selections are empty (zero length).OutOfRangeException - if row (& column as square matrix) selections are not valid.public static void checkDimension(int expected,
int actual)
expected - the expected dimensionactual - the actual dimensionDimensionMismatchException - if the provided dimension is not the one expectedpublic static void checkAdditionCompatible(AnyMatrix left, AnyMatrix right)
left - Left hand side matrix.right - Right hand side matrix.MatrixDimensionMismatchException - if the matrices are not addition
compatible.public static void checkSubtractionCompatible(AnyMatrix left, AnyMatrix right)
left - Left hand side matrix.right - Right hand side matrix.MatrixDimensionMismatchException - if the matrices are not subtraction
compatible.public static void checkMultiplicationCompatible(AnyMatrix left, AnyMatrix right)
left - Left hand side matrix.right - Right hand side matrix.DimensionMismatchException - if getColumnDimension(left) != getRowDimension(right)public static void checkMultiplicationCompatible(AnyMatrix left, AnyMatrix right, boolean rightToTransposed)
left - Left hand side matrix.right - Right hand side matrix.rightToTransposed - indicate if the right matrix will be transposed before the operationDimensionMismatchException - if getColumnDimension(left) != getRowDimension(right)public static Array2DRowRealMatrix fractionMatrixToRealMatrix(FieldMatrix<Fraction> m)
m - Matrix to convert.public static Array2DRowRealMatrix bigFractionMatrixToRealMatrix(FieldMatrix<BigFraction> m)
m - Matrix to convert.public static void serializeRealVector(RealVector vector, ObjectOutputStream oos) throws IOException
RealVector.
This method is intended to be called from within a private writeObject method (after a call to
oos.defaultWriteObject()) in a class that has a RealVector field, which should be declared
transient. This way, the default handling does not serialize the vector (the RealVector
interface is not serializable by default) but this method does serialize it specifically.
The following example shows how a simple class with a name and a real vector should be written:
public class NamedVector implements Serializable {
private final String name;
private final transient RealVector coefficients;
// omitted constructors, getters ...
private void writeObject(ObjectOutputStream oos) throws IOException {
oos.defaultWriteObject(); // takes care of name field
MatrixUtils.serializeRealVector(coefficients, oos);
}
private void readObject(ObjectInputStream ois) throws ClassNotFoundException, IOException {
ois.defaultReadObject(); // takes care of name field
MatrixUtils.deserializeRealVector(this, "coefficients", ois);
}
}
vector - real vector to serializeoos - stream where the real vector should be writtenIOException - if object cannot be written to streamdeserializeRealVector(Object, String, ObjectInputStream)public static void deserializeRealVector(Object instance, String fieldName, ObjectInputStream ois) throws IOException
RealVector field in a class.
This method is intended to be called from within a private readObject method (after a call to
ois.defaultReadObject()) in a class that has a RealVector field, which should be declared
transient. This way, the default handling does not deserialize the vector (the RealVector
interface is not serializable by default) but this method does deserialize it specifically.
instance - instance in which the field must be set upfieldName - name of the field within the class (may be private and final)ois - stream from which the real vector should be readIOException - if object cannot be read from the streamserializeRealVector(RealVector, ObjectOutputStream)public static void serializeRealMatrix(RealMatrix matrix, ObjectOutputStream oos) throws IOException
RealMatrix.
This method is intended to be called from within a private writeObject method (after a call to
oos.defaultWriteObject()) in a class that has a RealMatrix field, which should be declared
transient. This way, the default handling does not serialize the matrix (the RealMatrix
interface is not serializable by default) but this method does serialize it specifically.
The following example shows how a simple class with a name and a real matrix should be written:
public class NamedMatrix implements Serializable {
private final String name;
private final transient RealMatrix coefficients;
// omitted constructors, getters ...
private void writeObject(ObjectOutputStream oos) throws IOException {
oos.defaultWriteObject(); // takes care of name field
MatrixUtils.serializeRealMatrix(coefficients, oos);
}
private void readObject(ObjectInputStream ois) throws ClassNotFoundException, IOException {
ois.defaultReadObject(); // takes care of name field
MatrixUtils.deserializeRealMatrix(this, "coefficients", ois);
}
}
matrix - real matrix to serializeoos - stream where the real matrix should be writtenIOException - if object cannot be written to streamdeserializeRealMatrix(Object, String, ObjectInputStream)public static void deserializeRealMatrix(Object instance, String fieldName, ObjectInputStream ois) throws IOException
RealMatrix field in a class.
This method is intended to be called from within a private readObject method (after a call to
ois.defaultReadObject()) in a class that has a RealMatrix field, which should be declared
transient. This way, the default handling does not deserialize the matrix (the RealMatrix
interface is not serializable by default) but this method does deserialize it specifically.
instance - instance in which the field must be set upfieldName - name of the field within the class (may be private and final)ois - stream from which the real matrix should be readIOException - if object cannot be read from the streamserializeRealMatrix(RealMatrix, ObjectOutputStream)public static void solveLowerTriangularSystem(RealMatrix rm, RealVector b)
RealMatrix.
This method is called to solve systems of equations which are of the lower triangular form. The matrix
RealMatrix is assumed, though not checked, to be in lower triangular form. The vector RealVector
is overwritten with the solution. The matrix is checked that it is square and its dimensions match the length of
the vector.
rm - RealMatrix which is lower triangularb - RealVector this is overwrittenDimensionMismatchException - if the matrix and vector are not
conformableNonSquareMatrixException - if the matrix rm is not squareMathArithmeticException - if the absolute value of one of the diagonal
coefficient of rm is lower than Precision.SAFE_MINpublic static void solveUpperTriangularSystem(RealMatrix rm, RealVector b)
RealMatrix.
This method is called to solve systems of equations which are of the lower triangular form. The matrix
RealMatrix is assumed, though not checked, to be in upper triangular form. The vector RealVector
is overwritten with the solution. The matrix is checked that it is square and its dimensions match the length of
the vector.
rm - RealMatrix which is upper triangularb - RealVector this is overwrittenDimensionMismatchException - if the matrix and vector are not
conformableNonSquareMatrixException - if the matrix rm is not
squareMathArithmeticException - if the absolute value of one of the diagonal
coefficient of rm is lower than Precision.SAFE_MINpublic static RealMatrix blockInverse(RealMatrix m, int splitIndex)
m - Matrix whose inverse must be computed.splitIndex - Index that determines the "split" line and
column.
The element corresponding to this index will part of the
upper-left sub-matrix.m.NonSquareMatrixException - if m is not square.Copyright © 2021 CNES. All rights reserved.