Package io.bhagat.math.linearalgebra
Class Matrix
- java.lang.Object
-
- io.bhagat.math.linearalgebra.Matrix
-
- All Implemented Interfaces:
java.io.Serializable,java.lang.Comparable<Matrix>
public class Matrix extends java.lang.Object implements java.io.Serializable, java.lang.Comparable<Matrix>
A class representing a Matrix- Author:
- Bhagat
- See Also:
- Serialized Form
-
-
Nested Class Summary
Nested Classes Modifier and Type Class Description static classMatrix.EigenSolutionA class that holds both eigenvalues and eigenvectorsclassMatrix.IndexNotInMatrixExceptionAn exception for handling if a user attempts to access an index that does not exist in the matrixclassMatrix.InvalidShapeExceptionAn exception for if a matrix is not the proper size for a certain operationstatic classMatrix.MatrixIndexAn object that stores all the information about one index of the matrixstatic classMatrix.OuterProductSVDA class to hold all the parts of the outer product form of the SVDstatic classMatrix.SingularSolutionA class that holds both singular values and eigenvectors of Matrix.multiply(transpose(), this)
-
Field Summary
Fields Modifier and Type Field Description private intcolumnsthe number of columns in the matrix;private double[][]dataa 2D double array storing to internal data of the Matrixstatic doubleEPSILONprivate introwsthe number of rows in the matrix;private static longserialVersionUID
-
Method Summary
All Methods Static Methods Instance Methods Concrete Methods Modifier and Type Method Description Matrixadd(Matrix m)performs element wise additionMatrixclone()Clones this matrix with a new memory allocationMatrixcofactor()Finds the cofactor of the matrixstatic Matrixcofactor(Matrix A)finds the cofactor of a matrixintcompareTo(Matrix m)compares two matrices by determinantdoubledeterminant()uses the static method to compute the determinant of the matrixstatic doubledeterminant(Matrix m)Matrixdivide(double d)performs the scalar division on the matrixMatrixdivide(Matrix m)performs element wise divisionMatrix.EigenSolutioneigenproblem(int iterations)Solves the eigen problemdouble[]eigenvalues(int iterations)computes the eigenvalues of the matrixdouble[]eigenvaluestest(int iterations)private Vectoreigenvector(double eigenvalue)Vector[]eigenvectors(double[] eigenvalues)calculates the eigenvectors based on the eigenvalues providedbooleanequals(Matrix m)checks if two matrices have the same datadoubleget(int i, int j)Get a value at a specified row and columnvoidget(Matrix.MatrixIndex matrixIndex)Get a value using a matrixIndex and store that into the matrix indexintgetColumns()double[][]getData()intgetRows()Vector[]getVectorColumns()Vector[]getVectorRows()MatrixhadamardProduct(Matrix m)performs the hadamard product which is element wise multiplicationstatic MatrixhadamardProduct(Matrix a, Matrix b)Computes the hadamard product, which is element wise multiplicationstatic MatrixidentityMatrix(int size)generates an identity matrix with a specified sizestatic Matrixinner(Matrix a, Matrix b)performs the inner product on two matricesMatrixinverse()Finds the inverse of the matrixstatic Matrixinverse(Matrix A)computes the inverse matrix of the input matrixbooleanisSquare()Matrixmap(Function<java.lang.Double,java.lang.Double> function)maps a function onto each element in the matrixMatrixmapWithIndex(Function<Matrix.MatrixIndex,java.lang.Double> function)maps a function onto each element in the matrixMatrixmultiply(double d)performs the scalar multiplication on the matrixMatrixmultiply(Matrix m)performs matrix multiplicationstatic Matrixmultiply(Matrix a, Matrix b)Performs Matrix multiplicationstatic Matrixmultiply(Matrix A, Vector x)Performs Matrix multiplication with a matrix and a vectorMatrixmultiply(Vector v)performs matrix multiplicationstatic Matrixouter(Matrix a, Matrix b)performs the outer product on two matricesstatic Matrix[]QR(Matrix A)Computes the QR factorization of a matrixvoidrandomize()Fills the Matrix with random values from -1 to 1voidrandomize(double min, double max)Fills the Matrix with random values from min to maxMatrixreducedRowEchelonForm()converts the matrix to reduced row echelon formMatrixremoveColumn(int index)Removes a columns in the MatrixMatrixremoveRow(int index)Removes a row in the MatrixMatrixrowEchelonForm()converts the matrix to row echelon formvoidset(int i, int j, double value)Set a value at a specified row and columnvoidset(Matrix.MatrixIndex matrixIndex)Set a value using a matrix index objectMatrixsetColumn(Matrix m, int j)sets the column of the matrix to the values from the input matrixMatrixsetColumn(Vector v, int j)sets the column of the matrix to the values from the vectorMatrixsetColumns(Matrix[] ms)sets all the columns from an array of matricesMatrixsetColumns(Vector[] vs)sets all the columns from an array of vectorsvoidsetData(double[][] data)MatrixsetRow(Matrix m, int i)sets the row of the matrix to the values from the input matrixMatrixsetRow(Vector v, int i)sets the row of the matrix to the values from the vectorMatrixsetRows(Matrix[] ms)sets all the rows from an array of matricesMatrixsetRows(Vector[] vs)sets all the rows from an array of vectorsMatrix.SingularSolutionsingularSolution(int iterations)Finds both the singular values and corresponding eigenvectorsstatic Matrix[]singularValueDecomposition(Matrix A, int iterations)Performs singular value decomposition on a matrixstatic Matrix.OuterProductSVDsingularValueDecompositionOuter(Matrix A, int iterations)performs singular value decomposition and returns the output in outer product formdouble[]singularValues(int iterations)Find the singular values of a matrixMatrixsubtract(Matrix m)performs element wise subtractionjava.lang.StringtoString()VectortoVector()converts this matrix into a vectorMatrixtranspose()Transposes the matrixstatic Matrixtranspose(Matrix m)transposes the rows and columns of a matrix to the columns and rows
-
-
-
Field Detail
-
serialVersionUID
private static final long serialVersionUID
- See Also:
- Constant Field Values
-
data
private double[][] data
a 2D double array storing to internal data of the Matrix
-
rows
private int rows
the number of rows in the matrix;
-
columns
private int columns
the number of columns in the matrix;
-
EPSILON
public static final double EPSILON
- See Also:
- Constant Field Values
-
-
Constructor Detail
-
Matrix
public Matrix(int rows, int columns)Create a matrix with a specified number of rows and columns- Parameters:
rows- the rowscolumns- the columns
-
Matrix
public Matrix(double[][] data)
Create a matrix with specified data- Parameters:
data- the data in the form of a two dimensional double array
-
-
Method Detail
-
getVectorRows
public Vector[] getVectorRows()
- Returns:
- a list of vectors representing the rows of the matrix
-
getVectorColumns
public Vector[] getVectorColumns()
- Returns:
- a list of vectors representing the columns of the matrix
-
get
public double get(int i, int j) throws Matrix.IndexNotInMatrixExceptionGet a value at a specified row and column- Parameters:
i- the rowj- the column- Returns:
- the value
- Throws:
Matrix.IndexNotInMatrixException- when the indices accessed are not in the matrix
-
get
public void get(Matrix.MatrixIndex matrixIndex) throws Matrix.IndexNotInMatrixException
Get a value using a matrixIndex and store that into the matrix index- Parameters:
matrixIndex- the matrix index object- Throws:
Matrix.IndexNotInMatrixException- when the indices are not in the matrix
-
set
public void set(int i, int j, double value) throws Matrix.IndexNotInMatrixExceptionSet a value at a specified row and column- Parameters:
i- the rowj- the columnvalue- the value- Throws:
Matrix.IndexNotInMatrixException- if the index is invalid
-
setColumn
public Matrix setColumn(Matrix m, int j) throws Matrix.IndexNotInMatrixException
sets the column of the matrix to the values from the input matrix- Parameters:
m- the matrix to put into the columnj- the column index- Returns:
- a reference to this matrix
- Throws:
Matrix.IndexNotInMatrixException- if the sizes are not compatible
-
setColumn
public Matrix setColumn(Vector v, int j) throws Matrix.IndexNotInMatrixException
sets the column of the matrix to the values from the vector- Parameters:
v- the vector to put into the columnj- the column index- Returns:
- a reference to this matrix
- Throws:
Matrix.IndexNotInMatrixException- if the sizes are not compatible
-
setColumns
public Matrix setColumns(Vector[] vs)
sets all the columns from an array of vectors- Parameters:
vs- an array of the vectors to set into the Matrix- Returns:
- a reference to this matrix
-
setColumns
public Matrix setColumns(Matrix[] ms)
sets all the columns from an array of matrices- Parameters:
ms- an array of the matrices to set into the Matrix- Returns:
- a reference to this matrix
-
setRow
public Matrix setRow(Matrix m, int i) throws Matrix.IndexNotInMatrixException
sets the row of the matrix to the values from the input matrix- Parameters:
m- the matrix to put into the rowi- the row index- Returns:
- a reference to this matrix
- Throws:
Matrix.IndexNotInMatrixException- if the sizes are not compatible
-
setRow
public Matrix setRow(Vector v, int i) throws Matrix.IndexNotInMatrixException
sets the row of the matrix to the values from the vector- Parameters:
v- the vector to put into the rowi- the row index- Returns:
- a reference to this matrix
- Throws:
Matrix.IndexNotInMatrixException- if the sizes are not compatible
-
setRows
public Matrix setRows(Vector[] vs)
sets all the rows from an array of vectors- Parameters:
vs- an array of the vectors to set into the Matrix- Returns:
- a reference to this matrix
-
setRows
public Matrix setRows(Matrix[] ms)
sets all the rows from an array of matrices- Parameters:
ms- an array of the matrices to set into the Matrix- Returns:
- a reference to this matrix
-
set
public void set(Matrix.MatrixIndex matrixIndex) throws Matrix.IndexNotInMatrixException
Set a value using a matrix index object- Parameters:
matrixIndex- the matrix index object that holds all the index information- Throws:
Matrix.IndexNotInMatrixException- if the index is invalid
-
map
public Matrix map(Function<java.lang.Double,java.lang.Double> function)
maps a function onto each element in the matrix- Parameters:
function- the function to map- Returns:
- a reference of this matrix after the mapping
-
mapWithIndex
public Matrix mapWithIndex(Function<Matrix.MatrixIndex,java.lang.Double> function)
maps a function onto each element in the matrix- Parameters:
function- the function to map that receives MatrixIndex object- Returns:
- a reference of this matrix after the mapping
-
clone
public Matrix clone()
Clones this matrix with a new memory allocation- Overrides:
clonein classjava.lang.Object- Returns:
- the cloned matrix
-
randomize
public void randomize()
Fills the Matrix with random values from -1 to 1
-
randomize
public void randomize(double min, double max)Fills the Matrix with random values from min to max- Parameters:
min- the minimum random numbermax- the maximum random number
-
transpose
public Matrix transpose()
Transposes the matrix- Returns:
- the transposed matrix
-
inverse
public Matrix inverse()
Finds the inverse of the matrix- Returns:
- the inverse
-
cofactor
public Matrix cofactor()
Finds the cofactor of the matrix- Returns:
- the cofactor
-
multiply
public Matrix multiply(Matrix m)
performs matrix multiplication- Parameters:
m- the matrix to multiply with- Returns:
- the resultant matrix
-
multiply
public Matrix multiply(Vector v)
performs matrix multiplication- Parameters:
v- the vector to multiply with- Returns:
- the resultant matrix
-
removeRow
public Matrix removeRow(int index) throws Matrix.IndexNotInMatrixException
Removes a row in the Matrix- Parameters:
index- the index to remove the row at- Returns:
- the current matrix with the removed row
- Throws:
Matrix.IndexNotInMatrixException- if the removing index is out of bounds
-
removeColumn
public Matrix removeColumn(int index) throws Matrix.IndexNotInMatrixException
Removes a columns in the Matrix- Parameters:
index- the index to remove the row at- Returns:
- the current matrix with the removed columns
- Throws:
Matrix.IndexNotInMatrixException- if the removing index is out of bounds
-
eigenproblem
public Matrix.EigenSolution eigenproblem(int iterations)
Solves the eigen problem- Parameters:
iterations- the number of iterations for the QR algorithm- Returns:
- an object containing both the eigenvalues and eigenvectors
-
eigenvaluestest
public double[] eigenvaluestest(int iterations)
-
eigenvalues
public double[] eigenvalues(int iterations)
computes the eigenvalues of the matrixNote: this method may return extra eigenvalues that do not have a valid eigenvector. Use eigenproblem() for a better solution
- Parameters:
iterations- the number of iterations for the QR algorithm- Returns:
- the eigenvalues
-
eigenvectors
public Vector[] eigenvectors(double[] eigenvalues)
calculates the eigenvectors based on the eigenvalues provided- Parameters:
eigenvalues- the eigenvalues- Returns:
- the eigenvectors
-
eigenvector
private Vector eigenvector(double eigenvalue)
-
singularValues
public double[] singularValues(int iterations)
Find the singular values of a matrix- Parameters:
iterations- the number of iterations for the QR algorithm- Returns:
- the singular values of the matrix
-
singularSolution
public Matrix.SingularSolution singularSolution(int iterations)
Finds both the singular values and corresponding eigenvectors- Parameters:
iterations- the number of iterations for the QR algorithm- Returns:
- an object containing the singular values and eigenvectors
-
determinant
public double determinant() throws Matrix.InvalidShapeExceptionuses the static method to compute the determinant of the matrix- Returns:
- the determinant
- Throws:
Matrix.InvalidShapeException- gets thrown if it is not a square matrix
-
compareTo
public int compareTo(Matrix m)
compares two matrices by determinant- Specified by:
compareToin interfacejava.lang.Comparable<Matrix>- Parameters:
m- the matrix to compare to- Returns:
- the integer representing which determinant is greater
-
equals
public boolean equals(Matrix m)
checks if two matrices have the same data- Parameters:
m- the matrix to compare with- Returns:
- whether or not they are the same
-
hadamardProduct
public Matrix hadamardProduct(Matrix m)
performs the hadamard product which is element wise multiplication- Parameters:
m- the matrix to multiply- Returns:
- a reference to this matrix
-
multiply
public Matrix multiply(double d)
performs the scalar multiplication on the matrix- Parameters:
d- the scalar to multiply with- Returns:
- a reference to this matrix
-
divide
public Matrix divide(double d)
performs the scalar division on the matrix- Parameters:
d- the scalar to divide with- Returns:
- a reference to this matrix
-
rowEchelonForm
public Matrix rowEchelonForm()
converts the matrix to row echelon form- Returns:
- the matrix in row echelon form
-
reducedRowEchelonForm
public Matrix reducedRowEchelonForm()
converts the matrix to reduced row echelon form- Returns:
- the matrix in reduced row echelon form
-
add
public Matrix add(Matrix m)
performs element wise addition- Parameters:
m- the matrix to add with- Returns:
- a reference to this matrix
-
subtract
public Matrix subtract(Matrix m)
performs element wise subtraction- Parameters:
m- the matrix to subtract with- Returns:
- a reference to this matrix
-
divide
public Matrix divide(Matrix m)
performs element wise division- Parameters:
m- the matrix to divide with- Returns:
- a reference to this matrix
-
toVector
public Vector toVector()
converts this matrix into a vector- Returns:
- the vector
-
isSquare
public boolean isSquare()
- Returns:
- true if it is a square matrix
-
getData
public double[][] getData()
- Returns:
- the data
-
setData
public void setData(double[][] data)
- Parameters:
data- the data
-
getRows
public int getRows()
- Returns:
- the rows
-
getColumns
public int getColumns()
- Returns:
- the columns
-
toString
public java.lang.String toString()
- Overrides:
toStringin classjava.lang.Object- Returns:
- a string representation of the Matrix
-
multiply
public static Matrix multiply(Matrix a, Matrix b) throws Matrix.InvalidShapeException
Performs Matrix multiplication- Parameters:
a- first matrixb- second matrix- Returns:
- the resultant matrix
- Throws:
Matrix.InvalidShapeException- when a and b are invalid size for multiplication
-
multiply
public static Matrix multiply(Matrix A, Vector x) throws Matrix.InvalidShapeException
Performs Matrix multiplication with a matrix and a vector- Parameters:
A- the matrixx- the vector- Returns:
- the resultant matrix
- Throws:
Matrix.InvalidShapeException- when A and x are invalid size for multiplication
-
inner
public static Matrix inner(Matrix a, Matrix b)
performs the inner product on two matrices- Parameters:
a- a matrixb- another matrix- Returns:
- the matrix result
-
outer
public static Matrix outer(Matrix a, Matrix b)
performs the outer product on two matrices- Parameters:
a- a matrixb- another matrix- Returns:
- the matrix result
-
hadamardProduct
public static Matrix hadamardProduct(Matrix a, Matrix b) throws Matrix.InvalidShapeException
Computes the hadamard product, which is element wise multiplication- Parameters:
a- the first matrixb- the second matrix- Returns:
- the resultant matrix
- Throws:
Matrix.InvalidShapeException- if the matrices do not have the same shape
-
transpose
public static Matrix transpose(Matrix m)
transposes the rows and columns of a matrix to the columns and rows- Parameters:
m- the matrix to transpose- Returns:
- the transposed matrix
-
singularValueDecomposition
public static Matrix[] singularValueDecomposition(Matrix A, int iterations)
Performs singular value decomposition on a matrix- Parameters:
A- the matrix to find the SVD decomposition ofiterations- the number of iterations for the QR algorithm- Returns:
- an array of matrices that contain {U, Sigma, V}
-
singularValueDecompositionOuter
public static Matrix.OuterProductSVD singularValueDecompositionOuter(Matrix A, int iterations)
performs singular value decomposition and returns the output in outer product form- Parameters:
A- the matrix to factoriterations- the number of iterations for the QR algorithm- Returns:
- an object holding the solutions for the factorization
-
QR
public static Matrix[] QR(Matrix A)
Computes the QR factorization of a matrix- Parameters:
A- the matrix- Returns:
- an array of matrices where the first matrix is Q and the second one is R
-
determinant
public static double determinant(Matrix m) throws Matrix.InvalidShapeException
- Parameters:
m- the Matrix to take the determinant of- Returns:
- the determinant
- Throws:
Matrix.InvalidShapeException- if the matrix is not a square matrix
-
cofactor
public static Matrix cofactor(Matrix A)
finds the cofactor of a matrix- Parameters:
A- the matrix- Returns:
- the cofactor matrix
-
inverse
public static Matrix inverse(Matrix A)
computes the inverse matrix of the input matrix- Parameters:
A- the input matrix- Returns:
- the inverse of the input matrix
-
identityMatrix
public static Matrix identityMatrix(int size)
generates an identity matrix with a specified size- Parameters:
size- the size is the number of rows and columns- Returns:
- the generated matrix
-
-