Class MatrixUtils
- java.lang.Object
-
- org.apache.commons.math4.legacy.linear.MatrixUtils
-
public final class MatrixUtils extends Object
A collection of static methods that operate on or return matrices.
-
-
Field Summary
Fields Modifier and Type Field Description static RealMatrixFormatDEFAULT_FORMATThe default format forRealMatrixobjects.static RealMatrixFormatOCTAVE_FORMATA format forRealMatrixobjects compatible with octave.
-
Method Summary
All Methods Static Methods Concrete Methods Modifier and Type Method Description static RealMatrixblockInverse(RealMatrix m, int splitIndex)Computes the inverse of the given matrix by splitting it into 4 sub-matrices.static voidcheckAdditionCompatible(AnyMatrix left, AnyMatrix right)Check if matrices are addition compatible.static voidcheckColumnIndex(AnyMatrix m, int column)Check if a column index is valid.static voidcheckMatrixIndex(AnyMatrix m, int row, int column)Check if matrix indices are valid.static voidcheckMultiplicationCompatible(AnyMatrix left, AnyMatrix right)Check if matrices are multiplication compatible.static voidcheckRowIndex(AnyMatrix m, int row)Check if a row index is valid.static voidcheckSubMatrixIndex(AnyMatrix m, int[] selectedRows, int[] selectedColumns)Check if submatrix ranges indices are valid.static voidcheckSubMatrixIndex(AnyMatrix m, int startRow, int endRow, int startColumn, int endColumn)Check if submatrix ranges indices are valid.static voidcheckSubtractionCompatible(AnyMatrix left, AnyMatrix right)Check if matrices are subtraction compatible.static voidcheckSymmetric(RealMatrix matrix, double eps)Checks whether a matrix is symmetric.static <T extends FieldElement<T>>
FieldMatrix<T>createColumnFieldMatrix(T[] columnData)Creates a columnFieldMatrixusing the data from the input array.static RealMatrixcreateColumnRealMatrix(double[] columnData)Creates a columnRealMatrixusing the data from the input array.static <T extends FieldElement<T>>
FieldMatrix<T>createFieldDiagonalMatrix(T[] diagonal)Returns a diagonal matrix with specified elements.static <T extends FieldElement<T>>
FieldMatrix<T>createFieldIdentityMatrix(Field<T> field, int dimension)Returnsdimension x dimensionidentity matrix.static <T extends FieldElement<T>>
FieldMatrix<T>createFieldMatrix(Field<T> field, int rows, int columns)Returns aFieldMatrixwith specified dimensions.static <T extends FieldElement<T>>
FieldMatrix<T>createFieldMatrix(T[][] data)Returns aFieldMatrixwhose entries are the values in the the input array.static <T extends FieldElement<T>>
FieldVector<T>createFieldVector(T[] data)Creates aFieldVectorusing the data from the input array.static DiagonalMatrixcreateRealDiagonalMatrix(double[] diagonal)Creates a diagonal matrix with the specified diagonal elements.static RealMatrixcreateRealIdentityMatrix(int dimension)Returnsdimension x dimensionidentity matrix.static RealMatrixcreateRealMatrix(double[][] data)Returns aRealMatrixwhose entries are the values in the the input array.static RealMatrixcreateRealMatrix(int rows, int columns)Returns aRealMatrixwith specified dimensions.static RealMatrixcreateRealMatrixWithDiagonal(double[] diagonal)Creates a dense matrix with the specified diagonal elements.static RealVectorcreateRealVector(double[] data)Creates aRealVectorusing the data from the input array.static <T extends FieldElement<T>>
FieldMatrix<T>createRowFieldMatrix(T[] rowData)Create a rowFieldMatrixusing the data from the input array.static RealMatrixcreateRowRealMatrix(double[] rowData)Create a rowRealMatrixusing the data from the input array.static voiddeserializeRealMatrix(Object instance, String fieldName, ObjectInputStream ois)Deserialize aRealMatrixfield in a class.static voiddeserializeRealVector(Object instance, String fieldName, ObjectInputStream ois)Deserialize aRealVectorfield in a class.static RealMatrixinverse(RealMatrix matrix)Computes the inverse of the given matrix.static RealMatrixinverse(RealMatrix matrix, double threshold)Computes the inverse of the given matrix.static booleanisSymmetric(RealMatrix matrix, double eps)Checks whether a matrix is symmetric.static voidserializeRealMatrix(RealMatrix matrix, ObjectOutputStream oos)Serialize aRealMatrix.static voidserializeRealVector(RealVector vector, ObjectOutputStream oos)Serialize aRealVector.static voidsolveLowerTriangularSystem(RealMatrix rm, RealVector b)Solve a system of composed of a Lower Triangular MatrixRealMatrix.static voidsolveUpperTriangularSystem(RealMatrix rm, RealVector b)Solver a system composed of an Upper Triangular MatrixRealMatrix.
-
-
-
Field Detail
-
DEFAULT_FORMAT
public static final RealMatrixFormat DEFAULT_FORMAT
The default format forRealMatrixobjects.- Since:
- 3.1
-
OCTAVE_FORMAT
public static final RealMatrixFormat OCTAVE_FORMAT
A format forRealMatrixobjects compatible with octave.- Since:
- 3.1
-
-
Method Detail
-
createRealMatrix
public static RealMatrix createRealMatrix(int rows, int columns)
Returns aRealMatrixwith 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
Array2DRowRealMatrixinstance is built. Above this threshold aBlockRealMatrixinstance is built.The matrix elements are all set to 0.0.
- Parameters:
rows- number of rows of the matrixcolumns- number of columns of the matrix- Returns:
- RealMatrix with specified dimensions
- See Also:
createRealMatrix(double[][])
-
createFieldMatrix
public static <T extends FieldElement<T>> FieldMatrix<T> createFieldMatrix(Field<T> field, int rows, int columns)
Returns aFieldMatrixwith 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
FieldMatrixinstance is built. Above this threshold aBlockFieldMatrixinstance is built.The matrix elements are all set to field.getZero().
- Type Parameters:
T- the type of the field elements- Parameters:
field- field to which the matrix elements belongrows- number of rows of the matrixcolumns- number of columns of the matrix- Returns:
- FieldMatrix with specified dimensions
- Since:
- 2.0
- See Also:
createFieldMatrix(FieldElement[][])
-
createRealMatrix
public static RealMatrix createRealMatrix(double[][] data) throws NullArgumentException, DimensionMismatchException, NoDataException
Returns aRealMatrixwhose entries are 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
Array2DRowRealMatrixinstance is built. Above this threshold aBlockRealMatrixinstance is built.The input array is copied, not referenced.
- Parameters:
data- input array- Returns:
- RealMatrix containing the values of the array
- Throws:
DimensionMismatchException- ifdatais not rectangular (not all rows have the same length).NoDataException- if a row or column is empty.NullArgumentException- if eitherdataordata[0]isnull.DimensionMismatchException- ifdatais not rectangular.- See Also:
createRealMatrix(int, int)
-
createFieldMatrix
public static <T extends FieldElement<T>> FieldMatrix<T> createFieldMatrix(T[][] data) throws DimensionMismatchException, NoDataException, NullArgumentException
Returns aFieldMatrixwhose entries are 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
FieldMatrixinstance is built. Above this threshold aBlockFieldMatrixinstance is built.The input array is copied, not referenced.
- Type Parameters:
T- the type of the field elements- Parameters:
data- input array- Returns:
- a matrix containing the values of the array.
- Throws:
DimensionMismatchException- ifdatais not rectangular (not all rows have the same length).NoDataException- if a row or column is empty.NullArgumentException- if eitherdataordata[0]isnull.- Since:
- 2.0
- See Also:
createFieldMatrix(Field, int, int)
-
createRealIdentityMatrix
public static RealMatrix createRealIdentityMatrix(int dimension)
Returnsdimension x dimensionidentity matrix.- Parameters:
dimension- dimension of identity matrix to generate- Returns:
- identity matrix
- Throws:
IllegalArgumentException- if dimension is not positive- Since:
- 1.1
-
createFieldIdentityMatrix
public static <T extends FieldElement<T>> FieldMatrix<T> createFieldIdentityMatrix(Field<T> field, int dimension)
Returnsdimension x dimensionidentity matrix.- Type Parameters:
T- the type of the field elements- Parameters:
field- field to which the elements belongdimension- dimension of identity matrix to generate- Returns:
- identity matrix
- Throws:
IllegalArgumentException- if dimension is not positive- Since:
- 2.0
-
createRealDiagonalMatrix
public static DiagonalMatrix createRealDiagonalMatrix(double[] diagonal)
Creates a diagonal matrix with the specified diagonal elements.- Parameters:
diagonal- Diagonal elements of the matrix. The array elements will be copied.- Returns:
- a diagonal matrix instance.
- Since:
- 2.0
- See Also:
createRealMatrixWithDiagonal(double[])
-
createRealMatrixWithDiagonal
public static RealMatrix createRealMatrixWithDiagonal(double[] diagonal)
Creates a dense matrix with the specified diagonal elements.- Parameters:
diagonal- Diagonal elements of the matrix.- Returns:
- a matrix instance.
- Since:
- 4.0
- See Also:
createRealDiagonalMatrix(double[])
-
createFieldDiagonalMatrix
public static <T extends FieldElement<T>> FieldMatrix<T> createFieldDiagonalMatrix(T[] diagonal)
Returns a diagonal matrix with specified elements.- Type Parameters:
T- the type of the field elements- Parameters:
diagonal- diagonal elements of the matrix (the array elements will be copied)- Returns:
- diagonal matrix
- Since:
- 2.0
-
createRealVector
public static RealVector createRealVector(double[] data) throws NoDataException, NullArgumentException
Creates aRealVectorusing the data from the input array.- Parameters:
data- the input data- Returns:
- a data.length RealVector
- Throws:
NoDataException- ifdatais empty.NullArgumentException- ifdataisnull.
-
createFieldVector
public static <T extends FieldElement<T>> FieldVector<T> createFieldVector(T[] data) throws NoDataException, NullArgumentException, ZeroException
Creates aFieldVectorusing the data from the input array.- Type Parameters:
T- the type of the field elements- Parameters:
data- the input data- Returns:
- a data.length FieldVector
- Throws:
NoDataException- ifdatais empty.NullArgumentException- ifdataisnull.ZeroException- ifdatahas 0 elements
-
createRowRealMatrix
public static RealMatrix createRowRealMatrix(double[] rowData) throws NoDataException, NullArgumentException
Create a rowRealMatrixusing the data from the input array.- Parameters:
rowData- the input row data- Returns:
- a 1 x rowData.length RealMatrix
- Throws:
NoDataException- ifrowDatais empty.NullArgumentException- ifrowDataisnull.
-
createRowFieldMatrix
public static <T extends FieldElement<T>> FieldMatrix<T> createRowFieldMatrix(T[] rowData) throws NoDataException, NullArgumentException
Create a rowFieldMatrixusing the data from the input array.- Type Parameters:
T- the type of the field elements- Parameters:
rowData- the input row data- Returns:
- a 1 x rowData.length FieldMatrix
- Throws:
NoDataException- ifrowDatais empty.NullArgumentException- ifrowDataisnull.
-
createColumnRealMatrix
public static RealMatrix createColumnRealMatrix(double[] columnData) throws NoDataException, NullArgumentException
Creates a columnRealMatrixusing the data from the input array.- Parameters:
columnData- the input column data- Returns:
- a columnData x 1 RealMatrix
- Throws:
NoDataException- ifcolumnDatais empty.NullArgumentException- ifcolumnDataisnull.
-
createColumnFieldMatrix
public static <T extends FieldElement<T>> FieldMatrix<T> createColumnFieldMatrix(T[] columnData) throws NoDataException, NullArgumentException
Creates a columnFieldMatrixusing the data from the input array.- Type Parameters:
T- the type of the field elements- Parameters:
columnData- the input column data- Returns:
- a columnData x 1 FieldMatrix
- Throws:
NoDataException- ifdatais empty.NullArgumentException- ifcolumnDataisnull.
-
checkSymmetric
public static void checkSymmetric(RealMatrix matrix, double eps)
Checks whether a matrix is symmetric.- Parameters:
matrix- Matrix to check.eps- Relative tolerance.- Throws:
NonSquareMatrixException- if the matrix is not square.NonSymmetricMatrixException- if the matrix is not symmetric.- Since:
- 3.1
-
isSymmetric
public static boolean isSymmetric(RealMatrix matrix, double eps)
Checks whether a matrix is symmetric.- Parameters:
matrix- Matrix to check.eps- Relative tolerance.- Returns:
trueifmatrixis symmetric.- Since:
- 3.1
-
checkMatrixIndex
public static void checkMatrixIndex(AnyMatrix m, int row, int column) throws OutOfRangeException
Check if matrix indices are valid.- Parameters:
m- Matrix.row- Row index to check.column- Column index to check.- Throws:
OutOfRangeException- ifroworcolumnis not a valid index.
-
checkRowIndex
public static void checkRowIndex(AnyMatrix m, int row) throws OutOfRangeException
Check if a row index is valid.- Parameters:
m- Matrix.row- Row index to check.- Throws:
OutOfRangeException- ifrowis not a valid index.
-
checkColumnIndex
public static void checkColumnIndex(AnyMatrix m, int column) throws OutOfRangeException
Check if a column index is valid.- Parameters:
m- Matrix.column- Column index to check.- Throws:
OutOfRangeException- ifcolumnis not a valid index.
-
checkSubMatrixIndex
public static void checkSubMatrixIndex(AnyMatrix m, int startRow, int endRow, int startColumn, int endColumn) throws NumberIsTooSmallException, OutOfRangeException
Check if submatrix ranges indices are valid. Rows and columns are indicated counting from 0 ton - 1.- Parameters:
m- Matrix.startRow- Initial row index.endRow- Final row index.startColumn- Initial column index.endColumn- Final column index.- Throws:
OutOfRangeException- if the indices are invalid.NumberIsTooSmallException- ifendRow < startRoworendColumn < startColumn.
-
checkSubMatrixIndex
public static void checkSubMatrixIndex(AnyMatrix m, int[] selectedRows, int[] selectedColumns) throws NoDataException, NullArgumentException, OutOfRangeException
Check if submatrix ranges indices are valid. Rows and columns are indicated counting from 0 to n-1.- Parameters:
m- Matrix.selectedRows- Array of row indices.selectedColumns- Array of column indices.- Throws:
NullArgumentException- ifselectedRowsorselectedColumnsarenull.NoDataException- if the row or column selections are empty (zero length).OutOfRangeException- if row or column selections are not valid.
-
checkAdditionCompatible
public static void checkAdditionCompatible(AnyMatrix left, AnyMatrix right)
Check if matrices are addition compatible.- Parameters:
left- Left hand side matrix.right- Right hand side matrix.- Throws:
MatrixDimensionMismatchException- if the matrices are not addition compatible.
-
checkSubtractionCompatible
public static void checkSubtractionCompatible(AnyMatrix left, AnyMatrix right)
Check if matrices are subtraction compatible.- Parameters:
left- Left hand side matrix.right- Right hand side matrix.- Throws:
MatrixDimensionMismatchException- if the matrices are not addition compatible.
-
checkMultiplicationCompatible
public static void checkMultiplicationCompatible(AnyMatrix left, AnyMatrix right)
Check if matrices are multiplication compatible.- Parameters:
left- Left hand side matrix.right- Right hand side matrix.- Throws:
DimensionMismatchException- if matrices are not multiplication compatible.
-
serializeRealVector
public static void serializeRealVector(RealVector vector, ObjectOutputStream oos) throws IOException
Serialize aRealVector.This method is intended to be called from within a private
writeObjectmethod (after a call tooos.defaultWriteObject()) in a class that has aRealVectorfield, which should be declaredtransient. This way, the default handling does not serialize the vector (theRealVectorinterface 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); } }- Parameters:
vector- real vector to serializeoos- stream where the real vector should be written- Throws:
IOException- if object cannot be written to stream- See Also:
deserializeRealVector(Object, String, ObjectInputStream)
-
deserializeRealVector
public static void deserializeRealVector(Object instance, String fieldName, ObjectInputStream ois) throws ClassNotFoundException, IOException
Deserialize aRealVectorfield in a class.This method is intended to be called from within a private
readObjectmethod (after a call toois.defaultReadObject()) in a class that has aRealVectorfield, which should be declaredtransient. This way, the default handling does not deserialize the vector (theRealVectorinterface is not serializable by default) but this method does deserialize it specifically.- Parameters:
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 read- Throws:
ClassNotFoundException- if a class in the stream cannot be foundIOException- if object cannot be read from the stream- See Also:
serializeRealVector(RealVector, ObjectOutputStream)
-
serializeRealMatrix
public static void serializeRealMatrix(RealMatrix matrix, ObjectOutputStream oos) throws IOException
Serialize aRealMatrix.This method is intended to be called from within a private
writeObjectmethod (after a call tooos.defaultWriteObject()) in a class that has aRealMatrixfield, which should be declaredtransient. This way, the default handling does not serialize the matrix (theRealMatrixinterface 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); } }- Parameters:
matrix- real matrix to serializeoos- stream where the real matrix should be written- Throws:
IOException- if object cannot be written to stream- See Also:
deserializeRealMatrix(Object, String, ObjectInputStream)
-
deserializeRealMatrix
public static void deserializeRealMatrix(Object instance, String fieldName, ObjectInputStream ois) throws ClassNotFoundException, IOException
Deserialize aRealMatrixfield in a class.This method is intended to be called from within a private
readObjectmethod (after a call toois.defaultReadObject()) in a class that has aRealMatrixfield, which should be declaredtransient. This way, the default handling does not deserialize the matrix (theRealMatrixinterface is not serializable by default) but this method does deserialize it specifically.- Parameters:
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 read- Throws:
ClassNotFoundException- if a class in the stream cannot be foundIOException- if object cannot be read from the stream- See Also:
serializeRealMatrix(RealMatrix, ObjectOutputStream)
-
solveLowerTriangularSystem
public static void solveLowerTriangularSystem(RealMatrix rm, RealVector b) throws DimensionMismatchException, MathArithmeticException, NonSquareMatrixException
Solve a system of composed of a Lower Triangular MatrixRealMatrix.This method is called to solve systems of equations which are of the lower triangular form. The matrix
RealMatrixis assumed, though not checked, to be in lower triangular form. The vectorRealVectoris overwritten with the solution. The matrix is checked that it is square and its dimensions match the length of the vector.- Parameters:
rm- RealMatrix which is lower triangularb- RealVector this is overwritten- Throws:
DimensionMismatchException- if the matrix and vector are not conformableNonSquareMatrixException- if the matrixrmis not squareMathArithmeticException- if the absolute value of one of the diagonal coefficient ofrmis lower thanPrecision.SAFE_MIN
-
solveUpperTriangularSystem
public static void solveUpperTriangularSystem(RealMatrix rm, RealVector b) throws DimensionMismatchException, MathArithmeticException, NonSquareMatrixException
Solver a system composed of an Upper Triangular MatrixRealMatrix.This method is called to solve systems of equations which are of the lower triangular form. The matrix
RealMatrixis assumed, though not checked, to be in upper triangular form. The vectorRealVectoris overwritten with the solution. The matrix is checked that it is square and its dimensions match the length of the vector.- Parameters:
rm- RealMatrix which is upper triangularb- RealVector this is overwritten- Throws:
DimensionMismatchException- if the matrix and vector are not conformableNonSquareMatrixException- if the matrixrmis not squareMathArithmeticException- if the absolute value of one of the diagonal coefficient ofrmis lower thanPrecision.SAFE_MIN
-
blockInverse
public static RealMatrix blockInverse(RealMatrix m, int splitIndex)
Computes the inverse of the given matrix by splitting it into 4 sub-matrices.- Parameters:
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.- Returns:
- the inverse of
m. - Throws:
NonSquareMatrixException- ifmis not square.
-
inverse
public static RealMatrix inverse(RealMatrix matrix) throws NullArgumentException, SingularMatrixException, NonSquareMatrixException
Computes the inverse of the given matrix.By default, the inverse of the matrix is computed using the QR-decomposition, unless a more efficient method can be determined for the input matrix.
Note: this method will use a singularity threshold of 0, use
inverse(RealMatrix, double)if a different threshold is needed.- Parameters:
matrix- Matrix whose inverse shall be computed- Returns:
- the inverse of
matrix - Throws:
NullArgumentException- ifmatrixisnullSingularMatrixException- if m is singularNonSquareMatrixException- if matrix is not square- Since:
- 3.3
-
inverse
public static RealMatrix inverse(RealMatrix matrix, double threshold) throws NullArgumentException, SingularMatrixException, NonSquareMatrixException
Computes the inverse of the given matrix.By default, the inverse of the matrix is computed using the QR-decomposition, unless a more efficient method can be determined for the input matrix.
- Parameters:
matrix- Matrix whose inverse shall be computedthreshold- Singularity threshold- Returns:
- the inverse of
m - Throws:
NullArgumentException- ifmatrixisnullSingularMatrixException- if matrix is singularNonSquareMatrixException- if matrix is not square- Since:
- 3.3
-
-