Package com.irurueta.algebra
Class Matrix
java.lang.Object
com.irurueta.algebra.Matrix
- All Implemented Interfaces:
Serializable
,Cloneable
Defines a matrix of numerical data.
Values of a matrix are stored inside an internal array of data.
- See Also:
-
Field Summary
FieldsModifier and TypeFieldDescriptionprivate double[]
Array containing data of matrix.private int[]
Array used for indexing column start positions within buffer.private int
Number of matrix columns.static final boolean
Constant defining the default order in which values are stored in a matrix.private int
Number of matrix rows. -
Constructor Summary
Constructors -
Method Summary
Modifier and TypeMethodDescriptionvoid
Adds provided matrix to this instance.void
Adds another matrix to this matrix instance and stores the result in provided result matrix.addAndReturnNew
(Matrix other) Adds provided matrix to this instance and returns the result as a new matrix instance.clone()
Returns a new matrix instance containing the same data as this instance.void
Copies the contents of provided matrix into this instance.void
Copies this matrix data into provided matrix.static Matrix
createWithGaussianRandomValues
(int rows, int columns, double mean, double standardDeviation) Creates new matrix instance using provided size and containing gaussian/normal distributed random values with provided median and standard deviation.static Matrix
createWithGaussianRandomValues
(int rows, int columns, double mean, double standardDeviation, Random random) Creates new matrix instance using provided size and containing gaussian/normal distributed random values with provided median and standard deviation and using provided random generatorstatic Matrix
createWithUniformRandomValues
(int rows, int columns, double minValue, double maxValue) Creates new matrix instance using provided size and containing uniformly distributed random values with provided range.static Matrix
createWithUniformRandomValues
(int rows, int columns, double minValue, double maxValue, Random random) Creates new matrix instance using provided size and containing uniformly distributed random values with provided range and using provided random generatorstatic Matrix
diagonal
(double[] diagonal) Creates a diagonal matrix having all the elements in provided array in its diagonal and the remaining elements equal to zero.static void
Makes provided result matrix a diagonal matrix containing provided elements in the diagonal.void
elementByElementProduct
(Matrix other) Computes element by element product (i.e.void
elementByElementProduct
(Matrix other, Matrix result) Computes element by element product (i.e.Computes element by element product (i.e.boolean
Checks if provided matrix has exactly the same contents as this matrix instance.boolean
Checks if provided matrix has contents similar to this matrix by checking that all values have a maximum difference equal to provided threshold and same size.boolean
Checks if provided object is a Matrix instance having exactly the same contents as this matrix instance.static void
fillWithGaussianRandomValues
(double mean, double standardDeviation, Matrix result) Fills provided matrix with random Gaussian values with provided mean and standard deviationstatic void
fillWithGaussianRandomValues
(double mean, double standardDeviation, Random random, Matrix result) Fills provided matrix with random Gaussian values with provided mean and standard deviation.static void
fillWithUniformRandomValues
(double minValue, double maxValue, Matrix result) Fills provided matrix with random uniform values ranging from minValue to maxValue.static void
fillWithUniformRandomValues
(double minValue, double maxValue, Random random, Matrix result) Fills provided matrix with random uniform values ranging from minValue to maxValue.void
fromArray
(double[] array) Copies elements of array into this instance using column order.void
fromArray
(double[] array, boolean isColumnOrder) Copies elements of array into this instance using provided order.double[]
Returns current matrix internal buffer of data.int
Returns number of columns in matrix.double
getElementAt
(int row, int column) Obtains element in matrix located at position (row and column).double
getElementAtIndex
(int index) Obtains element in matrix located at provided index value using the order specified by DEFAULT_USE_COLUMN_ORDER.double
getElementAtIndex
(int index, boolean isColumnOrder) Obtain element in matrix located at provided index value using provided order (either column or row order).int
getIndex
(int row, int column) Returns index within internal buffer corresponding to provided row and column positions.int
getRows()
Returns number of rows in matrix.getSubmatrix
(int topLeftRow, int topLeftColumn, int bottomRightRow, int bottomRightColumn) Obtains a sub-matrix of current matrix instance.void
getSubmatrix
(int topLeftRow, int topLeftColumn, int bottomRightRow, int bottomRightColumn, Matrix result) Obtains a sub-matrix of current matrix instance.double[]
getSubmatrixAsArray
(int topLeftRow, int topLeftColumn, int bottomRightRow, int bottomRightColumn) Obtains sub-matrix of current matrix instance as an array of values using DEFAULT_USE_COLUMN_ORDER.double[]
getSubmatrixAsArray
(int topLeftRow, int topLeftColumn, int bottomRightRow, int bottomRightColumn, boolean isColumnOrder) Obtains sub-matrix of current matrix instance as an array of values using provided order.void
getSubmatrixAsArray
(int topLeftRow, int topLeftColumn, int bottomRightRow, int bottomRightColumn, boolean isColumnOrder, double[] array) Retrieves a sub-matrix of current matrix instance as an array of values using provided column order and storing the result in provided array.void
getSubmatrixAsArray
(int topLeftRow, int topLeftColumn, int bottomRightRow, int bottomRightColumn, double[] array) Retrieves a sub-matrix of current matrix instance as an array of values using column order and storing the result in provided array.int
hashCode()
Computes and returns hash code for this instance.static Matrix
identity
(int rows, int columns) Creates and returns a new matrix instance having all the elements on the diagonal equal to one and the remaining ones equal to zero.static void
Sets values into provided matrix to make it an identity matrix (all elements in the diagonal equal to one, and remaining elements to zero).void
initialize
(double initValue) Sets the contents of this matrix to provided value in all of its elementsprivate void
internalAdd
(Matrix other, Matrix result) Method to internally add two matrices.private void
internalElementByElementProduct
(Matrix other, Matrix result) Method to internally compute element by element product of two matrices.private void
internalGetSubmatrix
(int topLeftRow, int topLeftColumn, int bottomRightRow, int bottomRightColumn, Matrix result) Internal method to retrieve a sub-matrix of current matrix instance.private void
internalGetSubmatrixAsArray
(int topLeftRow, int topLeftColumn, int bottomRightRow, int bottomRightColumn, boolean isColumnOrder, double[] result) Internal method to retrieve a sub-matrix of current matrix instance as an array of values using provided column order and storing the result in provided array.private void
internalMultiply
(Matrix other, double[] resultBuffer, int[] resultColumnIndex) Method to internally multiply two matrices.private void
internalMultiply
(Matrix other, Matrix result) Method to internally multiply two matrices.private void
internalMultiplyKronecker
(Matrix other, double[] resultBuffer, int[] resultColumnIndex) Method to internally compute the Kronecker product between two matrices.private void
internalMultiplyKronecker
(Matrix other, Matrix result) Method to internally compute the Kronecker product between two matrices.private void
internalResize
(int rows, int columns) Method used internally to remove matrix contents and resizing it.private void
internalSubtract
(Matrix other, Matrix result) Method to internally subtract two matrices.private void
internalTranspose
(double[] resultBuffer, int[] resultColumnIndex) Method to internally compute matrix transposition.private void
internalTranspose
(Matrix result) Method to internally compute matrix transposition.void
Multiplies this matrix with provided matrix.void
Multiplies another matrix to this matrix instance and stores the result in provided result matrix.multiplyAndReturnNew
(Matrix other) Multiplies this matrix with provided matrix and returns the result as a new instance.void
multiplyByScalar
(double scalar) Computes product by scalar of this instance multiplying all its elements by provided scalar value and returning the result as a new instance.private void
multiplyByScalar
(double scalar, Matrix result) Computes product by scalar of this instance multiplying all its elements by provided scalar value and storing the results in provided result matrix.multiplyByScalarAndReturnNew
(double scalar) Computes product by scalar of this instance multiplying all its elements by provided scalar value and returning the result as a new instance.void
multiplyKronecker
(Matrix other) Computes the Kronecker product of this matrix with provided matrix and updates this matrix with the result of the multiplication.void
multiplyKronecker
(Matrix other, Matrix result) Computes the Kronecker product with provided matrix and stores the result in provided result matrix.Computes the Kronecker product with provided matrix and returns the result as a new instance.static Matrix
newFromArray
(double[] array) Instantiates new matrix from array using DEFAULT_USE_COLUMN_ORDERstatic Matrix
newFromArray
(double[] array, boolean isColumnOrder) Instantiates new matrix from array using either column or row ordervoid
reset
(int rows, int columns, double initValue) Resets current instance by removing its contents, resizing it to provided size and setting all its elements to provided value.void
resize
(int rows, int columns) Resizes current instance by removing its contents and resizing it to provided size.void
setElementAt
(int row, int column, double value) Sets element in matrix located at provided position (row and column).void
setElementAtIndex
(int index, double value) Sets element in matrix located at provided index using the order specified by DEFAULT_USE_COLUMN_ORDER.void
setElementAtIndex
(int index, double value, boolean isColumnOrder) Sets element in matrix located at provided index using provided order (either column or row order).void
setSubmatrix
(int topLeftRow, int topLeftColumn, int bottomRightRow, int bottomRightColumn, double value) Sets elements in provided region to provided value.void
setSubmatrix
(int topLeftRow, int topLeftColumn, int bottomRightRow, int bottomRightColumn, double[] values) Copies elements from provided array into this matrix at provided location.void
setSubmatrix
(int topLeftRow, int topLeftColumn, int bottomRightRow, int bottomRightColumn, double[] values, boolean isColumnOrder) Copies elements from provided array into this matrix at provided location.void
setSubmatrix
(int topLeftRow, int topLeftColumn, int bottomRightRow, int bottomRightColumn, double[] values, int valuesStart, int valuesEnd) Copies elements from provided array into this matrix at provided location.void
setSubmatrix
(int topLeftRow, int topLeftColumn, int bottomRightRow, int bottomRightColumn, double[] values, int valuesStart, int valuesEnd, boolean isColumnOrder) Copies elements from provided array into this matrix at provided location.void
setSubmatrix
(int topLeftRow, int topLeftColumn, int bottomRightRow, int bottomRightColumn, Matrix submatrix) Copies elements from provided sub-matrix into this matrix at provided location.void
setSubmatrix
(int topLeftRow, int topLeftColumn, int bottomRightRow, int bottomRightColumn, Matrix submatrix, int submatrixTopLeftRow, int submatrixTopLeftColumn, int submatrixBottomRightRow, int submatrixBottomRightColumn) Copies elements from provided sub-matrix into this matrix at provided locationvoid
Subtracts provided matrix from this instance.void
Subtracts another matrix from this matrix instance and stores the result in provided result matrix.subtractAndReturnNew
(Matrix other) Subtracts provided matrix from this instance and returns the result as a new matrix instance.void
Symmetrizes this instance and updates it with computed value.void
symmetrize
(Matrix result) Symmetrizes this instance and stores the result into provided instance.Symmetrizes this instance and returns the result as a new matrix instance.double[]
toArray()
Returns the contents of the matrix as an array of values using DEFAULT_USE_COLUMN_ORDER to pick elements.double[]
toArray
(boolean isColumnOrder) Returns the contents of the matrix as an array of values using provided order to pick elements.void
toArray
(double[] result) Copies the contents of the matrix to an array of values using column order.void
toArray
(double[] result, boolean isColumnOrder) Copies the contents of the matrix to an array of values using provided order to pick elements.void
Transposes current matrix.void
Transposes current matrix and stores result in provided matrix.Transposes current matrix and returns result as a new instance.
-
Field Details
-
DEFAULT_USE_COLUMN_ORDER
public static final boolean DEFAULT_USE_COLUMN_ORDERConstant defining the default order in which values are stored in a matrix. This can be useful when copying data to and from an array.- See Also:
-
rows
private int rowsNumber of matrix rows. -
columns
private int columnsNumber of matrix columns. -
buffer
private double[] bufferArray containing data of matrix. Data is stored linearly in memory using column order. -
columnIndex
private int[] columnIndexArray used for indexing column start positions within buffer. This is used for faster access to matrix elements.
-
-
Constructor Details
-
Matrix
Constructor of this class. By default, when instantiating a matrix its values are undefined.- Parameters:
rows
- Defines number of rows in matrix.columns
- Defines number of columns in matrix.- Throws:
WrongSizeException
- Exception thrown if matrix must be empty with provided size. In other words, matrices must have at least one row and one column. Leaving number of rows or columns to zero will raise this exception.
-
Matrix
Copy constructor.- Parameters:
m
- matrix to copy from.
-
-
Method Details
-
getRows
public int getRows()Returns number of rows in matrix.- Returns:
- Number of rows in matrix.
-
getColumns
public int getColumns()Returns number of columns in matrix.- Returns:
- Number of columns in matrix.
-
getElementAt
public double getElementAt(int row, int column) Obtains element in matrix located at position (row and column). Notice that row and column position are zero-indexed.- Parameters:
row
- Row to be used for element location.column
- Column to be used for element location.- Returns:
- Value of element in matrix located at provided position.
- Throws:
ArrayIndexOutOfBoundsException
- Exception raised if attempting to access a location that lies outside the boundaries of the internal array containing matrix data. Notice that internal data is stored in column order, hence, if row position exceeds the number of rows in the matrix, this exception might not be raised depending on column position, however, if the column value exceeds the number of columns, it will always raise the exception.
-
getIndex
public int getIndex(int row, int column) Returns index within internal buffer corresponding to provided row and column positions.- Parameters:
row
- row to be used for element location.column
- column to be used for element location.- Returns:
- index within internal buffer.
-
getElementAtIndex
public double getElementAtIndex(int index) Obtains element in matrix located at provided index value using the order specified by DEFAULT_USE_COLUMN_ORDER. Note: an index indicates linear position within matrix, in layman terms, if using column order, then position (i, j), where i stands for row index and j for column index, becomes index = j * rows + 1. On the other hand, if using row order then index becomes index = i * columns + j.- Parameters:
index
- Linear position.- Returns:
- Value of element contained at provided position.
- Throws:
ArrayIndexOutOfBoundsException
- Exception raised if index lays outside valid values, which range from zero (inclusive) to rows * columns (exclusive)
-
getElementAtIndex
public double getElementAtIndex(int index, boolean isColumnOrder) Obtain element in matrix located at provided index value using provided order (either column or row order).- Parameters:
index
- Linear position.isColumnOrder
- if true indicates that values are retrieved assuming that are stored in column order.- Returns:
- Value of element contained at provided position.
- Throws:
ArrayIndexOutOfBoundsException
- Exception raised if index lays outside valid values, which range from zero (inclusive) to rows * columns (exclusive)
-
setElementAt
public void setElementAt(int row, int column, double value) Sets element in matrix located at provided position (row and column).- Parameters:
row
- Row to be used for element location to be set.column
- Column to be used for element location to be set.value
- Value to be set at provided position.- Throws:
ArrayIndexOutOfBoundsException
- Exception raised if attempting to access a location that lies outside the boundaries of the internal array containing matrix data. Notice that internal data is stored in column order, hence, if row position exceeds the number of rows in the matrix, this exception might not be raised depending on column position, however, if the column value exceeds the number of columns, it will always raise the exception.
-
setElementAtIndex
public void setElementAtIndex(int index, double value) Sets element in matrix located at provided index using the order specified by DEFAULT_USE_COLUMN_ORDER. Note: an index indicates linear position within matrix, in layman terms, if using column order, then position (i, j), where i stands for row index and j for column index, becomes index = j * rows + 1. On the other hand, if using row order then index becomes index = i * columns + j.- Parameters:
index
- Linear position.value
- Value of element contained at provided position.- Throws:
ArrayIndexOutOfBoundsException
- Exception raised if index lays outside valid values, which range from zero (inclusive) to rows * columns (exclusive)
-
setElementAtIndex
public void setElementAtIndex(int index, double value, boolean isColumnOrder) Sets element in matrix located at provided index using provided order (either column or row order).- Parameters:
index
- Linear position.value
- Value of element to be set at provided position.isColumnOrder
- if true indicates that values are retrieved assuming that are stored in column order.- Throws:
ArrayIndexOutOfBoundsException
- Exception raised if index lays outside valid values, which range from zero (inclusive) to rows * columns (exclusive).
-
clone
Returns a new matrix instance containing the same data as this instance.- Overrides:
clone
in classObject
- Returns:
- A copy of this matrix instance.
- Throws:
CloneNotSupportedException
- if clone fails.
-
copyTo
Copies this matrix data into provided matrix. Provided output matrix will be resized if needed.- Parameters:
output
- Destination matrix where data will be copied to.- Throws:
NullPointerException
- Exception raised if provided output matrix is null.
-
copyFrom
Copies the contents of provided matrix into this instance. This instance will be resized if needed.- Parameters:
input
- Input matrix where data will be copied from.- Throws:
NullPointerException
- Exception raised if provided input matrix is null.
-
add
Adds another matrix to this matrix instance and stores the result in provided result matrix. If provided result matrix doesn't have proper size, it will be resized.- Parameters:
other
- Matrix to be added to current instance.result
- Matrix where result of summation is stored.- Throws:
WrongSizeException
- Exception thrown if provided matrix to be added (i.e. other) does not have the same size as this matrix.NullPointerException
- Exception raised if provided matrices are null.
-
addAndReturnNew
Adds provided matrix to this instance and returns the result as a new matrix instance.- Parameters:
other
- Matrix to be added.- Returns:
- Returns a new matrix containing the sum of this matrix with provided matrix.
- Throws:
WrongSizeException
- Exception raised if provided matrix does not have the same size as this matrix.NullPointerException
- Exception raised if provided matrix is null.
-
add
Adds provided matrix to this instance.- Parameters:
other
- Matrix to be added.- Throws:
WrongSizeException
- Exception raised if provided matrix does not have the same size as this matrix.NullPointerException
- Exception raised if provided matrix is null.
-
subtract
Subtracts another matrix from this matrix instance and stores the result in provided result matrix. If provided result matrix doesn't have proper size, it will be resized.- Parameters:
other
- Matrix to be added to current instance.result
- Matrix where result of subtraction is stored.- Throws:
WrongSizeException
- Exception thrown if provided matrix to be subtracted (i.e. other) does not have the same size as this matrix.NullPointerException
- Exception raised if provided matrices are null.
-
subtractAndReturnNew
Subtracts provided matrix from this instance and returns the result as a new matrix instance.- Parameters:
other
- Matrix to be subtracted from.- Returns:
- Returns a new matrix containing the subtraction of provided matrix from this matrix.
- Throws:
WrongSizeException
- Exception raised if provided matrix does not have the same size as this matrix.NullPointerException
- Exception raised if provided matrix is null.
-
subtract
Subtracts provided matrix from this instance.- Parameters:
other
- Matrix to be subtracted from.- Throws:
WrongSizeException
- Exception raised if provided matrix does not have the same size as this matrix.NullPointerException
- Exception raised if provided matrix is null.
-
multiply
Multiplies another matrix to this matrix instance and stores the result in provided result matrix. If provided result matrix doesn't have proper size, it will be resized.- Parameters:
other
- Matrix to be multiplied to current instance.result
- Matrix where result of product is stored.- Throws:
WrongSizeException
- Exception thrown when current and provided matrix (i.e. other) has incompatible size for product computation.NullPointerException
- Exception raised if provided matrices are null.
-
multiplyAndReturnNew
Multiplies this matrix with provided matrix and returns the result as a new instance. If this matrix m1 has size m x n and provided matrix m2 has size p x q, then n must be equal to p so that product m1 * m2 can be correctly computed obtaining a matrix of size m x q, otherwise an IllegalArgumentException will be raised.- Parameters:
other
- Right operand of matrix product- Returns:
- Matrix containing result of multiplication
- Throws:
WrongSizeException
- Exception thrown when current and provided matrices have incompatible sizes for product computation.NullPointerException
- Exception thrown if provided matrix is null
-
multiply
Multiplies this matrix with provided matrix. If this matrix m1 has size m x n and provided matrix m2 has size p x q, then n must be equal to p so that product m1 * m2 can be correctly computed resizing this matrix to a new one having size m x q, otherwise an IllegalArgumentException will be raised.- Parameters:
other
- Right operand of matrix product- Throws:
WrongSizeException
- Exception thrown when current and provided matrices have incompatible sizes for product computation.NullPointerException
- Exception thrown if provided matrix is null
-
multiplyKronecker
Computes the Kronecker product with provided matrix and stores the result in provided result matrix. If provided result matrix doesn't have proper size, it will be resized.- Parameters:
other
- other matrix to be Kronecker multiplied to current matrix.result
- matrix where result will be stored.
-
multiplyKroneckerAndReturnNew
Computes the Kronecker product with provided matrix and returns the result as a new instance. If this matrix m1 has size mxn and provided matrix m2 has size pxq, the resulting matrix will be m*pxn*q.- Parameters:
other
- other matrix to be Kronecker multiplied to current matrix.- Returns:
- matrix containing result of Kronecker multiplication.
-
multiplyKronecker
Computes the Kronecker product of this matrix with provided matrix and updates this matrix with the result of the multiplication. If this matrix m1 has size mxn and provided matrix m2 has size pxq, the resulting matrix will be resized to m*pxn*q.- Parameters:
other
- other matrix to be Kronecker multiplied to current matrix.
-
multiplyByScalar
Computes product by scalar of this instance multiplying all its elements by provided scalar value and storing the results in provided result matrix. If provided result matrix doesn't have proper size, it will be automatically resized.- Parameters:
scalar
- Scalar amount that current matrix will be multiplied by.result
- Matrix where result of operation is stored.
-
multiplyByScalarAndReturnNew
Computes product by scalar of this instance multiplying all its elements by provided scalar value and returning the result as a new instance.- Parameters:
scalar
- Scalar amount that current matrix will be multiplied by.- Returns:
- Returns a new matrix instance that contains result of product by scalar.
-
multiplyByScalar
public void multiplyByScalar(double scalar) Computes product by scalar of this instance multiplying all its elements by provided scalar value and returning the result as a new instance.- Parameters:
scalar
- Scalar amount that current matrix will be multiplied by.
-
equals
Checks if provided object is a Matrix instance having exactly the same contents as this matrix instance. -
hashCode
public int hashCode()Computes and returns hash code for this instance. Hash codes are almost unique values that are useful for fast classification and storage of objects in collections. -
equals
Checks if provided matrix has exactly the same contents as this matrix instance.- Parameters:
other
- Matrix to be compared.- Returns:
- Returns true if both objects are considered to be equal (same content and size)
-
equals
Checks if provided matrix has contents similar to this matrix by checking that all values have a maximum difference equal to provided threshold and same size.- Parameters:
other
- Matrix to be comparedthreshold
- Maximum difference allowed between values on same position to determine that matrices are equal- Returns:
- True if matrices are considered to be equal (almost equal content and same size)
-
elementByElementProduct
Computes element by element product (i.e. Hadamard product) between current and provided (i.e. other) matrix, and stores the result in provided result matrix.- Parameters:
other
- Instance that will be used for element by element product with current instance.result
- Matrix where result of operation is stored.- Throws:
WrongSizeException
- Exception raised if attempting to perform element by element product on matrices of different size.NullPointerException
- Exception raised if provided matrix is null
-
elementByElementProductAndReturnNew
Computes element by element product (i.e. Hadamard product) between current and provided instances and returns the result as a new instance. Example: Having matrices [1, 2, 3] [10, 11, 12] m1 = [4, 5, 6] m2 = [13, 14, 15] [7, 8, 9] [16, 17, 18] Then their element by element product will be [10, 22, 36 ] m3 = [52, 70, 90 ] [112, 136, 162]Note: Attempting to perform element product on matrices of different size will raise an IllegalArgumentException
- Parameters:
other
- Instance that will be used for element by element product with current instance.- Returns:
- A new Matrix containing element by element product result
- Throws:
WrongSizeException
- Exception raised if attempting to perform element by element product on matrices of different size.NullPointerException
- Exception raised if provided matrix is null
-
elementByElementProduct
Computes element by element product (i.e. Hadamard product) between current and provided instances. Example: Having matrices [1, 2, 3] [10, 11, 12] m1 = [4, 5, 6] m2 = [13, 14, 15] [7, 8, 9] [16, 17, 18] Then their element by element product will be [10, 22, 36 ] m3 = [52, 70, 90 ] [112, 136, 162]Note: Attempting to perform element product on matrices of different size will raise an IllegalArgumentException
- Parameters:
other
- Instance that will be used for element by element product with current instance.- Throws:
WrongSizeException
- Exception raised if attempting to perform element by element product on matrices of different size.NullPointerException
- Exception raised if provided matrix is null
-
transpose
Transposes current matrix and stores result in provided matrix. If provided matrix doesn't have proper size, it will be resized.- Parameters:
result
- Instance where transposed matrix is stored.
-
transposeAndReturnNew
Transposes current matrix and returns result as a new instance. Transposition of a matrix is done by exchanging rows and columns, in Layman terms, given a matrix m1 with elements located at m1(i,j), where i is the row index and j is the column index, then it follows that its transposed matrix m2 has the following property m2(i,j) = m1(j, i).- Returns:
- A new Matrix instance containing transposed matrix.
-
transpose
public void transpose()Transposes current matrix. Transposition of a matrix is done by exchanging rows and columns, in Layman terms, given a matrix m1 with elements located at m1(i,j), where i is the row index and j is the column index, then it follows that its transposed matrix m2 has the following property m2(i,j) = m1(j, i). -
initialize
public void initialize(double initValue) Sets the contents of this matrix to provided value in all of its elements- Parameters:
initValue
- Value to be set on all the elements of this matrix.
-
resize
Resizes current instance by removing its contents and resizing it to provided size.- Parameters:
rows
- Number of rows to be setcolumns
- Number of columns to be set- Throws:
WrongSizeException
- Exception raised if either rows or columns is zero.
-
reset
Resets current instance by removing its contents, resizing it to provided size and setting all its elements to provided value.- Parameters:
rows
- Number of rows to be setcolumns
- Number of columns to be setinitValue
- Value to be set in all of its elements- Throws:
WrongSizeException
- Exception raised if either rows or columns is zero.
-
toArray
public double[] toArray()Returns the contents of the matrix as an array of values using DEFAULT_USE_COLUMN_ORDER to pick elements.- Returns:
- Contents of matrix as an array
-
toArray
public double[] toArray(boolean isColumnOrder) Returns the contents of the matrix as an array of values using provided order to pick elements.- Parameters:
isColumnOrder
- If true, picks elements from matrix using column order, otherwise row order is used.- Returns:
- Contents of matrix as an array,
-
toArray
Copies the contents of the matrix to an array of values using column order.- Parameters:
result
- array where values will be copied to.- Throws:
WrongSizeException
- if provided result array does not have the same number of elements as the matrix (i.e. rows x columns).
-
toArray
Copies the contents of the matrix to an array of values using provided order to pick elements.- Parameters:
result
- array where values will be copied to.isColumnOrder
- if true, picks elements from matrix using column order, otherwise row order is used.- Throws:
WrongSizeException
- if provided result array does not have the same number of elements as the matrix (i.e. rows x columns).
-
getBuffer
public double[] getBuffer()Returns current matrix internal buffer of data.- Returns:
- Internal buffer of data.
-
getSubmatrix
public void getSubmatrix(int topLeftRow, int topLeftColumn, int bottomRightRow, int bottomRightColumn, Matrix result) Obtains a sub-matrix of current matrix instance. Sub-matrix is obtained by copying all elements contained within provided coordinates (both top-left and bottom-right points are included within sub-matrix).- Parameters:
topLeftRow
- Top-left row index where sub-matrix starts.topLeftColumn
- Top-left column index where sub-matrix starts.bottomRightRow
- Bottom-right row index where sub-matrix ends.bottomRightColumn
- Bottom-right column index where sub-matrix ends.result
- Instance where sub-matrix data is stored.- Throws:
IllegalArgumentException
- Exception raised whenever top-left or bottom-right corners lie outside current matrix instance, or if top-left corner is indeed located below or at right side of bottom-right corner.NullPointerException
- If provided result matrix is null.
-
getSubmatrix
public Matrix getSubmatrix(int topLeftRow, int topLeftColumn, int bottomRightRow, int bottomRightColumn) Obtains a sub-matrix of current matrix instance. Sub-matrix is obtained by copying all elements contained within provided coordinates (both top-left and bottom-right points are included within sub-matrix).- Parameters:
topLeftRow
- Top-left row index where sub-matrix starts.topLeftColumn
- Top-left column index where sub-matrix starts.bottomRightRow
- Bottom-right row index where sub-matrix ends.bottomRightColumn
- Bottom-right column index where sub-matrix ends.- Returns:
- A new instance containing selected sub-matrix.
- Throws:
IllegalArgumentException
- Exception raised whenever top-left or bottom-right corners lie outside current matrix instance, or if top-left corner is indeed located belo or at right side of bottom-right corner.
-
getSubmatrixAsArray
public void getSubmatrixAsArray(int topLeftRow, int topLeftColumn, int bottomRightRow, int bottomRightColumn, double[] array) throws WrongSizeException Retrieves a sub-matrix of current matrix instance as an array of values using column order and storing the result in provided array. Sub-matrix is obtained by copying all elements contained within provided coordinates (both top-left and bottom-right points are included within sub-matrix).- Parameters:
topLeftRow
- Top-left row index where sub-matrix startstopLeftColumn
- Top-left column index where sub-matrix startsbottomRightRow
- Bottom-right row index where sub-matrix endsbottomRightColumn
- Bottom-right column index where sub-matrix ends.array
- Array where sub-matrix data is stored.- Throws:
IllegalArgumentException
- Thrown if provided coordinates lie outside of matrix boundaries or if top-left corner is at the bottom or right side of bottom-right cornerWrongSizeException
- thrown if length of provided array does not match the number of elements to be extracted from this matrix
-
getSubmatrixAsArray
public void getSubmatrixAsArray(int topLeftRow, int topLeftColumn, int bottomRightRow, int bottomRightColumn, boolean isColumnOrder, double[] array) throws WrongSizeException Retrieves a sub-matrix of current matrix instance as an array of values using provided column order and storing the result in provided array. Sub-matrix is obtained by copying all elements contained within provided coordinates (both top-left and bottom-right points are included within sub-matrix).- Parameters:
topLeftRow
- Top-left row index where sub-matrix startstopLeftColumn
- Top-left column index where sub-matrix startsbottomRightRow
- Bottom-right row index where sub-matrix endsbottomRightColumn
- Bottom-right column index where sub-matrix ends.isColumnOrder
- If true, picks elements from matrix using column order, otherwise row order is used.array
- Array where sub-matrix data is stored.- Throws:
IllegalArgumentException
- Exception raised whenever top-left or bottom-right corners lie outside current matrix instance, or if top-left corner is indeed located below or at right side of bottom-right corner.WrongSizeException
- If provided array doesn't have proper length, which must be equal to the amount of elements in desired sub-matrix.
-
getSubmatrixAsArray
public double[] getSubmatrixAsArray(int topLeftRow, int topLeftColumn, int bottomRightRow, int bottomRightColumn) Obtains sub-matrix of current matrix instance as an array of values using DEFAULT_USE_COLUMN_ORDER. Array is obtained by copying all elements contained within provided coordinates (both top-left and bottom-right points are included within sub-matrix).- Parameters:
topLeftRow
- Top-left row index where sub-matrix startstopLeftColumn
- Top-left column index where sub-matrix startsbottomRightRow
- Bottom-right row index where sub-matrix endsbottomRightColumn
- Bottom-right column index where sub-matrix ends.- Returns:
- An array containing sub-matrix elements
- Throws:
IllegalArgumentException
- Exception raised whenever top-left or bottom-right corners lie outside current matrix instance, or if top-left corner is indeed located belo or at right side of bottom-right corner.
-
getSubmatrixAsArray
public double[] getSubmatrixAsArray(int topLeftRow, int topLeftColumn, int bottomRightRow, int bottomRightColumn, boolean isColumnOrder) Obtains sub-matrix of current matrix instance as an array of values using provided order. Array is obtained by copying all elements contained within provided coordinates (both top-left and bottom-right points are included within sub-matrix).- Parameters:
topLeftRow
- Top-left row index where sub-matrix startstopLeftColumn
- Top-left column index where sub-matrix startsbottomRightRow
- Bottom-right row index where sub-matrix endsbottomRightColumn
- Bottom-right column index where sub-matrix ends.isColumnOrder
- If true, picks elements from matrix using column order, otherwise row order is used.- Returns:
- An array containing sub-matrix elements
- Throws:
IllegalArgumentException
- Exception raised whenever top-left or bottom-right corners lie outside current matrix instance, or if top-left corner is indeed located below or at right side of bottom-right corner.
-
setSubmatrix
public void setSubmatrix(int topLeftRow, int topLeftColumn, int bottomRightRow, int bottomRightColumn, Matrix submatrix) Copies elements from provided sub-matrix into this matrix at provided location.- Parameters:
topLeftRow
- Top-left row index where sub-matrix copy startstopLeftColumn
- Top-left column index where sub-matrix copy startsbottomRightRow
- Bottom-right row index where sub-matrix copy endsbottomRightColumn
- Bottom-right column index where sub-matrix copy ends.submatrix
- Sub-matrix to be copied- Throws:
IllegalArgumentException
- Exception raised whenever top-left or bottom-right corners lie outside current matrix instance, or if top-left corner is indeed located below or at right side of bottom-right corner.
-
setSubmatrix
public void setSubmatrix(int topLeftRow, int topLeftColumn, int bottomRightRow, int bottomRightColumn, Matrix submatrix, int submatrixTopLeftRow, int submatrixTopLeftColumn, int submatrixBottomRightRow, int submatrixBottomRightColumn) Copies elements from provided sub-matrix into this matrix at provided location- Parameters:
topLeftRow
- Top-left row index where sub-matrix copy startstopLeftColumn
- Top-left column index where sub-matrix copy startsbottomRightRow
- Bottom-right row index where sub-matrix copy endsbottomRightColumn
- Bottom-right column index where sub-matrix copy ends.submatrix
- Sub-matrix to be copiedsubmatrixTopLeftRow
- Top-left row index of sub-matrix where copy startssubmatrixTopLeftColumn
- Top-left column index of sub-matrix where copy startssubmatrixBottomRightRow
- Bottom-right row index of sub-matrix where copy endssubmatrixBottomRightColumn
- Bottom-right column index of sub-matrix where copy ends- Throws:
IllegalArgumentException
- Exception raised whenever top-left or bottom-right corners lie outside current or provided matrices, or if top-left corners are indeed located below or at right side of bottom-right corners.
-
setSubmatrix
public void setSubmatrix(int topLeftRow, int topLeftColumn, int bottomRightRow, int bottomRightColumn, double value) Sets elements in provided region to provided value.- Parameters:
topLeftRow
- Top-left row index of region (inclusive).topLeftColumn
- Top-left column index of region (inclusive).bottomRightRow
- Bottom-right row index of region (inclusive).bottomRightColumn
- Bottom-right column index of region (inclusive).value
- Value to be set.- Throws:
IllegalArgumentException
- Exception raised whenever top-left or bottom-right corners lie outside current matrix instance, or if top-left corner is indeed located below or at right side of bottom-right corner.
-
setSubmatrix
public void setSubmatrix(int topLeftRow, int topLeftColumn, int bottomRightRow, int bottomRightColumn, double[] values) Copies elements from provided array into this matrix at provided location. Elements in array are copied into this matrix considering DEFAULT_USE_COLUMN_ORDER.- Parameters:
topLeftRow
- Top-left row index where copy starts.topLeftColumn
- Top-left column index where copy starts.bottomRightRow
- Bottom-right row index where copy ends.bottomRightColumn
- Bottom-right column index where copy ends.values
- Array to be copied.- Throws:
IllegalArgumentException
- Exception raised whenever top-left or bottom-right corners lie outside current matrix instance, or if top-left corner is indeed located below or at right side of bottom-right corner.
-
setSubmatrix
public void setSubmatrix(int topLeftRow, int topLeftColumn, int bottomRightRow, int bottomRightColumn, double[] values, boolean isColumnOrder) Copies elements from provided array into this matrix at provided location. Elements in array are copied into this matrix following provided order (either row or column order).- Parameters:
topLeftRow
- Top-left row index where copy starts.topLeftColumn
- Top-left column index where copy ends.bottomRightRow
- Bottom-right row index where copy ends.bottomRightColumn
- Bottom-right column index where copy ends.values
- Array to be copied.isColumnOrder
- If true values are copied consecutively from array following column order on the destination matrix, otherwise row order is used.- Throws:
IllegalArgumentException
- Exception raised whenever top-left or bottom-right corners lie outside current matrix instance, or if top-left corner is indeed located below or at right side of bottom-right corner.
-
setSubmatrix
public void setSubmatrix(int topLeftRow, int topLeftColumn, int bottomRightRow, int bottomRightColumn, double[] values, int valuesStart, int valuesEnd) Copies elements from provided array into this matrix at provided location. Elements in array are copied into this matrix considering DEFAULT_USE_COLUMN_ORDER starting at provided location until end provided position.- Parameters:
topLeftRow
- Top-left row index where copy starts (inclusive).topLeftColumn
- Top-left column index where copy starts (inclusive).bottomRightRow
- Bottom-right row index where copy ends (inclusive).bottomRightColumn
- Bottom-right column index where copy ends. (inclusive)values
- Array to be copied.valuesStart
- Position where copy from array will start (inclusive).valuesEnd
- Position where copy from array will finish (inclusive).- Throws:
IllegalArgumentException
- Exception raised whenever top-left or bottom-right corners lie outside current matrix instance, or if top-left corner is indeed located below or at right side of bottom-right corner, or if valuesStart and valuesEnd lie outside valid array positions or start is greater than end position.
-
setSubmatrix
public void setSubmatrix(int topLeftRow, int topLeftColumn, int bottomRightRow, int bottomRightColumn, double[] values, int valuesStart, int valuesEnd, boolean isColumnOrder) Copies elements from provided array into this matrix at provided location. Elements in array are copied into this matrix following provided order (either row or column order) starting at provided location until end provided position.- Parameters:
topLeftRow
- Top-left row index where copy starts (inclusive)topLeftColumn
- Top-left column index where copy starts (inclusive)bottomRightRow
- Bottom-right row index where copy ends (inclusive)bottomRightColumn
- Bottom-right column index where copy ends. (inclusive)values
- Array to be copied.valuesStart
- Position where copy from array will start (inclusive).valuesEnd
- Position where copy from array will finish (inclusive).isColumnOrder
- If true values are copied consecutively from array following column order on the destination matrix, otherwise row order is used.- Throws:
IllegalArgumentException
- Exception raised whenever top-left or bottom-right corners lie outside current matrix instance, or if top-left corner is indeed located below or at right side of bottom-right corner, or if valuesStart and valuesEnd lie outside valid array positions or start is greater than end position.
-
identity
Sets values into provided matrix to make it an identity matrix (all elements in the diagonal equal to one, and remaining elements to zero).- Parameters:
m
- Matrix where identity values are set.
-
identity
Creates and returns a new matrix instance having all the elements on the diagonal equal to one and the remaining ones equal to zero.- Parameters:
rows
- Number of rows of created instancecolumns
- Number of columns of created instance- Returns:
- An identity matrix
- Throws:
WrongSizeException
- Raised if either rows or columns is equal to zero
-
fillWithUniformRandomValues
public static void fillWithUniformRandomValues(double minValue, double maxValue, Random random, Matrix result) Fills provided matrix with random uniform values ranging from minValue to maxValue.- Parameters:
minValue
- Minimum value of uniform random generated valuesmaxValue
- Maximum value of uniform random generated valuesrandom
- Random generatorresult
- Matrix where random values are stored.- Throws:
IllegalArgumentException
- if minValue <= maxValueNullPointerException
- if either provided random or result instances are null
-
fillWithUniformRandomValues
Fills provided matrix with random uniform values ranging from minValue to maxValue.- Parameters:
minValue
- Minimum value of uniform random generated valuesmaxValue
- Maximum value of uniform random generated valuesresult
- Matrix where random values are stored- Throws:
IllegalArgumentException
- if minValue <= maxValueNullPointerException
- if provided result matrix is null
-
createWithUniformRandomValues
public static Matrix createWithUniformRandomValues(int rows, int columns, double minValue, double maxValue) throws WrongSizeException Creates new matrix instance using provided size and containing uniformly distributed random values with provided range.- Parameters:
rows
- Number of rows of instantiated matrixcolumns
- Number of columns of instantiated matrixminValue
- Minimum value of uniform random generated valuesmaxValue
- Maximum value of uniform random generated values- Returns:
- A new matrix containing uniform random values
- Throws:
WrongSizeException
- Exception thrown if either rows or columns is zero, or if the minimum random value is greater or equal than the maximum random valueIllegalArgumentException
- if minValue <= maxValue
-
createWithUniformRandomValues
public static Matrix createWithUniformRandomValues(int rows, int columns, double minValue, double maxValue, Random random) throws WrongSizeException Creates new matrix instance using provided size and containing uniformly distributed random values with provided range and using provided random generator- Parameters:
rows
- Number of rows of instantiated matrixcolumns
- Number of columns of instantiated matrixminValue
- Minimum value of uniform random generated valuesmaxValue
- Maximum value of uniform random generated valuesrandom
- A random generator.- Returns:
- A new matrix containing uniform random values
- Throws:
WrongSizeException
- Exception thrown if either rows or columns is zero, or if the minimum random value is greater or equal than the maximum random valueIllegalArgumentException
- if minValue <= maxValue
-
fillWithGaussianRandomValues
public static void fillWithGaussianRandomValues(double mean, double standardDeviation, Random random, Matrix result) Fills provided matrix with random Gaussian values with provided mean and standard deviation.- Parameters:
mean
- Mean value of generated random valuesstandardDeviation
- Standard deviation of generated random valuesrandom
- Random generatorresult
- Matrix where random values are stored- Throws:
IllegalArgumentException
- if standard deviation is negative or zeroNullPointerException
- if provided result matrix is null
-
fillWithGaussianRandomValues
public static void fillWithGaussianRandomValues(double mean, double standardDeviation, Matrix result) Fills provided matrix with random Gaussian values with provided mean and standard deviation- Parameters:
mean
- Mean value of generated random valuesstandardDeviation
- Standard deviation of generated random valuesresult
- Matrix where random values are stored- Throws:
IllegalArgumentException
- if standard deviation is negative or zeroNullPointerException
- if provided result matrix is null
-
createWithGaussianRandomValues
public static Matrix createWithGaussianRandomValues(int rows, int columns, double mean, double standardDeviation) throws WrongSizeException Creates new matrix instance using provided size and containing gaussian/normal distributed random values with provided median and standard deviation.- Parameters:
rows
- Number of rows of instantiated matrixcolumns
- Number of columns of instantiated matrixmean
- Mean value of gaussian random generated valuesstandardDeviation
- Standard deviation of gaussian random generated values- Returns:
- A new matrix containing gaussian random values
- Throws:
WrongSizeException
- Exception thrown if either rows or columns is zero, or if the standard deviation is negative or zero.IllegalArgumentException
- thrown if provided standard deviation is negative or zero.
-
createWithGaussianRandomValues
public static Matrix createWithGaussianRandomValues(int rows, int columns, double mean, double standardDeviation, Random random) throws WrongSizeException Creates new matrix instance using provided size and containing gaussian/normal distributed random values with provided median and standard deviation and using provided random generator- Parameters:
rows
- Number of rows of instantiated matrixcolumns
- Number of columns of instantiated matrixmean
- Mean value of gaussian random generated valuesstandardDeviation
- Standard deviation of gaussian random generated valuesrandom
- A random generator.- Returns:
- A new matrix containing gaussian random values
- Throws:
WrongSizeException
- Exception thrown if either rows or columns is zero, or if the standard deviation is negative or zero.IllegalArgumentException
- thrown if provided standard deviation is negative or zero.
-
diagonal
Makes provided result matrix a diagonal matrix containing provided elements in the diagonal. Elements outside the diagonal will be set to zero- Parameters:
diagonal
- Array containing the elements to be set on the diagonalresult
- Matrix where values are stored- Throws:
NullPointerException
- Exception thrown if provided parameters are null
-
diagonal
Creates a diagonal matrix having all the elements in provided array in its diagonal and the remaining elements equal to zero. Returned matrix will have size n x n, where n is the length of the array- Parameters:
diagonal
- Array containing the elements to be set on the diagonal- Returns:
- A diagonal matrix
- Throws:
NullPointerException
- Raised if provided diagonal array is null
-
newFromArray
Instantiates new matrix from array using DEFAULT_USE_COLUMN_ORDER- Parameters:
array
- Array used as source to copy values from- Returns:
- Returns matrix created from array
-
newFromArray
Instantiates new matrix from array using either column or row order- Parameters:
array
- Array used as source to copy values fromisColumnOrder
- True if column order must be used, false otherwise- Returns:
- Returns matrix created from array
-
fromArray
Copies elements of array into this instance using column order.- Parameters:
array
- array to copy values from.- Throws:
WrongSizeException
- if provided array length is not equal to the number of rows multiplied per the number of columns of this instance.
-
fromArray
Copies elements of array into this instance using provided order.- Parameters:
array
- array to copy values from.isColumnOrder
- true to use column order, false otherwise.- Throws:
WrongSizeException
- if provided array length is not equal to the number of rows multiplied per the number of columns of this instance.
-
symmetrize
Symmetrizes this instance and stores the result into provided instance. Symmetrization is done by averaging this instance with its transpose (i.e. S = (M+M')/2- Parameters:
result
- instance where symmetrized version of this instance will be stored.- Throws:
WrongSizeException
- if this instance is not square or provided result instance doesn't have the same size as this instance.
-
symmetrizeAndReturnNew
Symmetrizes this instance and returns the result as a new matrix instance. Symmetrization is done by averaging this instance with its transpose (i.e. S = (M+M')/2- Returns:
- a new symmetrizes version of this instance.
- Throws:
WrongSizeException
- if this instance is not square.
-
symmetrize
Symmetrizes this instance and updates it with computed value. Symmetrization is done by averaging this instance with its transpose (i.e. S = (M+M')/2- Throws:
WrongSizeException
- if this instance is not square.
-
internalAdd
Method to internally add two matrices.- Parameters:
other
- Matrix to be added to current matrixresult
- Matrix where result will be stored.
-
internalSubtract
Method to internally subtract two matrices.- Parameters:
other
- Matrix to be subtracted from current matrix.result
- Matrix where result will be stored.
-
internalMultiply
Method to internally multiply two matrices.- Parameters:
other
- Matrix to be multiplied to current matrixresultBuffer
- Matrix buffer of data where result will be stored.resultColumnIndex
- Array of matrix column indices where result will be stored.
-
internalMultiply
Method to internally multiply two matrices.- Parameters:
other
- Matrix to be multiplied to current matrix.result
- Matrix where result will be stored.
-
internalMultiplyKronecker
private void internalMultiplyKronecker(Matrix other, double[] resultBuffer, int[] resultColumnIndex) Method to internally compute the Kronecker product between two matrices.- Parameters:
other
- other matrix to be Kronecker multiplied to current matrix.resultBuffer
- matrix buffer of data where result will be stored.resultColumnIndex
- array of matrix column indices where result will be stored.
-
internalMultiplyKronecker
Method to internally compute the Kronecker product between two matrices.- Parameters:
other
- other matrix to be Kronecker multiplied to current matrix.result
- matrix where result will be stored.
-
internalElementByElementProduct
Method to internally compute element by element product of two matrices.- Parameters:
other
- Matrix to be element by element multiplied to current matrixresult
- Matrix where result will be stored.
-
internalTranspose
private void internalTranspose(double[] resultBuffer, int[] resultColumnIndex) Method to internally compute matrix transposition.- Parameters:
resultBuffer
- Buffer where transposed matrix data is stored.resultColumnIndex
- Buffer where indices of transposed matrix data is stored.
-
internalTranspose
Method to internally compute matrix transposition.- Parameters:
result
- Matrix where transposed data is stored.
-
internalResize
Method used internally to remove matrix contents and resizing it.- Parameters:
rows
- Number of rows to be setcolumns
- Number of columns to be set.- Throws:
WrongSizeException
- Exception raised if either rows or columns is zero.
-
internalGetSubmatrix
private void internalGetSubmatrix(int topLeftRow, int topLeftColumn, int bottomRightRow, int bottomRightColumn, Matrix result) Internal method to retrieve a sub-matrix of current matrix instance. Sub-matrix is obtained by copying all elements contained within provided coordinates (both top-left and bottom-right points are included within sub-matrix).- Parameters:
topLeftRow
- Top-left row index where sub-matrix starts.topLeftColumn
- Top-left column index where sub-matrix starts.bottomRightRow
- Bottom-right row index where sub-matrix ends.bottomRightColumn
- Bottom-right column index where sub-matrix ends.result
- Instance where sub-matrix data is stored.
-
internalGetSubmatrixAsArray
private void internalGetSubmatrixAsArray(int topLeftRow, int topLeftColumn, int bottomRightRow, int bottomRightColumn, boolean isColumnOrder, double[] result) Internal method to retrieve a sub-matrix of current matrix instance as an array of values using provided column order and storing the result in provided array. Sub-matrix is obtained by copying all elements contained within provided coordinates (both top-left and bottom-right points are included within sub-matrix).- Parameters:
topLeftRow
- Top-left row index where sub-matrix startstopLeftColumn
- Top-left column index where sub-matrix startsbottomRightRow
- Bottom-right row index where sub-matrix endsbottomRightColumn
- Bottom-right column index where sub-matrix ends.isColumnOrder
- If true, picks elements from matrix using column order, otherwise row order is used.result
- Array where sub-matrix data is stored.
-