Class Matrix
- All Implemented Interfaces:
Serializable
,Cloneable
,RevisionHandler
- Direct Known Subclasses:
ConfusionMatrix
The Java Matrix Class provides the fundamental operations of numerical linear algebra. Various constructors create Matrices from two dimensional arrays of double precision floating point numbers. Various "gets" and "sets" provide access to submatrices and matrix elements. Several methods implement basic matrix arithmetic, including matrix addition and multiplication, matrix norms, and element-by-element array operations. Methods for reading and printing matrices are also included. All the operations in this version of the Matrix Class involve real matrices. Complex matrices may be handled in a future version.
Five fundamental matrix decompositions, which consist of pairs or triples of matrices, permutation vectors, and the like, produce results in five decomposition classes. These decompositions are accessed by the Matrix class to compute solutions of simultaneous linear equations, determinants, inverses and other matrix functions. The five decompositions are:
- Cholesky Decomposition of symmetric, positive definite matrices.
- LU Decomposition of rectangular matrices.
- QR Decomposition of rectangular matrices.
- Singular Value Decomposition of rectangular matrices.
- Eigenvalue Decomposition of both symmetric and nonsymmetric square matrices.
- Example of use:
- Solve a linear system A x = b and compute the residual norm, ||b - A x||.
double[][] vals = { { 1., 2., 3 }, { 4., 5., 6. }, { 7., 8., 10. } }; Matrix A = new Matrix(vals); Matrix b = Matrix.random(3, 1); Matrix x = A.solve(b); Matrix r = A.times(x).minus(b); double rnorm = r.normInf();
@author
tag.- Version:
- $Revision: 10203 $
- Author:
- The Mathworks and NIST, Fracpete (fracpete at waikato dot ac dot nz)
- See Also:
-
Constructor Summary
ConstructorDescriptionMatrix
(double[][] A) Construct a matrix from a 2-D array.Matrix
(double[][] A, int m, int n) Construct a matrix quickly without checking arguments.Matrix
(double[] vals, int m) Construct a matrix from a one-dimensional packed arrayMatrix
(int m, int n) Construct an m-by-n matrix of zeros.Matrix
(int m, int n, double s) Construct an m-by-n constant matrix.Reads a matrix from a reader. -
Method Summary
Modifier and TypeMethodDescriptionElement-by-element left division, C = A.\BElement-by-element left division in place, A = A.\BElement-by-element right division, C = A./BElement-by-element right division in place, A = A./BarrayTimes
(Matrix B) Element-by-element multiplication, C = A.*BElement-by-element multiplication in place, A = A.*Bchol()
Cholesky Decompositionclone()
Clone the Matrix object.double
cond()
Matrix condition (2 norm)static Matrix
constructWithCopy
(double[][] A) Construct a matrix from a copy of a 2-D array.copy()
Make a deep copy of a matrixdouble
det()
Matrix determinanteig()
Eigenvalue Decompositiondouble
get
(int i, int j) Get a single element.double[][]
getArray()
Access the internal two-dimensional array.double[][]
Copy the internal two-dimensional array.int
Get column dimension.double[]
Make a one-dimensional column packed copy of the internal array.getMatrix
(int[] r, int[] c) Get a submatrix.getMatrix
(int[] r, int j0, int j1) Get a submatrix.getMatrix
(int i0, int i1, int[] c) Get a submatrix.getMatrix
(int i0, int i1, int j0, int j1) Get a submatrix.Returns the revision string.int
Get row dimension.double[]
Make a one-dimensional row packed copy of the internal array.static Matrix
identity
(int m, int n) Generate identity matrixinverse()
Matrix inverse or pseudoinverseboolean
isSquare()
returns whether the matrix is a square matrix or not.boolean
Returns true if the matrix is symmetric.lu()
LU Decompositionstatic void
Main method for testing this class.C = A - BA = A - Bdouble
norm1()
One normdouble
norm2()
Two normdouble
normF()
Frobenius normdouble
normInf()
Infinity normstatic Matrix
parseMatlab
(String matlab) creates a matrix from the given Matlab string.C = A + BplusEquals
(Matrix B) A = A + Bvoid
print
(int w, int d) Print the matrix to stdout.void
print
(PrintWriter output, int w, int d) Print the matrix to the output stream.void
print
(PrintWriter output, NumberFormat format, int width) Print the matrix to the output stream.void
print
(NumberFormat format, int width) Print the matrix to stdout.qr()
QR Decompositionstatic Matrix
random
(int m, int n) Generate matrix with random elementsint
rank()
Matrix rankstatic Matrix
read
(BufferedReader input) Read a matrix from a stream.regression
(Matrix y, double ridge) Performs a (ridged) linear regression.final LinearRegression
regression
(Matrix y, double[] w, double ridge) Performs a weighted (ridged) linear regression.void
set
(int i, int j, double s) Set a single element.void
Set a submatrix.void
Set a submatrix.void
Set a submatrix.void
Set a submatrix.Solve A*X = BSolve X*A = B, which is also A'*X' = B'sqrt()
returns the square root of the matrix, i.e., X from the equation X*X = A.
Steps in the Calculation (seesqrtm
in Matlab):
perform eigenvalue decomposition
[V,D]=eig(A) take the square root of all elements in D (only the ones with positive sign are considered for further computation)
S=sqrt(D) calculate the root
X=V*S/V, which can be also written as X=(V'\(V*S)')'svd()
Singular Value Decompositiontimes
(double s) Multiply a matrix by a scalar, C = s*ALinear algebraic matrix multiplication, A * BtimesEquals
(double s) Multiply a matrix by a scalar in place, A = s*AtoMatlab()
converts the Matrix into a single line Matlab string: matrix is enclosed by parentheses, rows are separated by semicolon and single cells by blanks, e.g., [1 2; 3 4].toString()
Converts a matrix to a string.double
trace()
Matrix trace.Matrix transpose.uminus()
Unary minusvoid
Writes out a matrix.
-
Constructor Details
-
Matrix
public Matrix(int m, int n) Construct an m-by-n matrix of zeros.- Parameters:
m
- Number of rows.n
- Number of colums.
-
Matrix
public Matrix(int m, int n, double s) Construct an m-by-n constant matrix.- Parameters:
m
- Number of rows.n
- Number of colums.s
- Fill the matrix with this scalar value.
-
Matrix
public Matrix(double[][] A) Construct a matrix from a 2-D array.- Parameters:
A
- Two-dimensional array of doubles.- Throws:
IllegalArgumentException
- All rows must have the same length- See Also:
-
Matrix
public Matrix(double[][] A, int m, int n) Construct a matrix quickly without checking arguments.- Parameters:
A
- Two-dimensional array of doubles.m
- Number of rows.n
- Number of colums.
-
Matrix
public Matrix(double[] vals, int m) Construct a matrix from a one-dimensional packed array- Parameters:
vals
- One-dimensional array of doubles, packed by columns (ala Fortran).m
- Number of rows.- Throws:
IllegalArgumentException
- Array length must be a multiple of m.
-
Matrix
Reads a matrix from a reader. The first line in the file should contain the number of rows and columns. Subsequent lines contain elements of the matrix. (FracPete: taken from old weka.core.Matrix class)- Parameters:
r
- the reader containing the matrix- Throws:
Exception
- if an error occurs- See Also:
-
-
Method Details
-
constructWithCopy
Construct a matrix from a copy of a 2-D array.- Parameters:
A
- Two-dimensional array of doubles.- Throws:
IllegalArgumentException
- All rows must have the same length
-
copy
Make a deep copy of a matrix -
clone
Clone the Matrix object. -
getArray
public double[][] getArray()Access the internal two-dimensional array.- Returns:
- Pointer to the two-dimensional array of matrix elements.
-
getArrayCopy
public double[][] getArrayCopy()Copy the internal two-dimensional array.- Returns:
- Two-dimensional array copy of matrix elements.
-
getColumnPackedCopy
public double[] getColumnPackedCopy()Make a one-dimensional column packed copy of the internal array.- Returns:
- Matrix elements packed in a one-dimensional array by columns.
-
getRowPackedCopy
public double[] getRowPackedCopy()Make a one-dimensional row packed copy of the internal array.- Returns:
- Matrix elements packed in a one-dimensional array by rows.
-
getRowDimension
public int getRowDimension()Get row dimension.- Returns:
- m, the number of rows.
-
getColumnDimension
public int getColumnDimension()Get column dimension.- Returns:
- n, the number of columns.
-
get
public double get(int i, int j) Get a single element.- Parameters:
i
- Row index.j
- Column index.- Returns:
- A(i,j)
- Throws:
ArrayIndexOutOfBoundsException
-
getMatrix
Get a submatrix.- Parameters:
i0
- Initial row indexi1
- Final row indexj0
- Initial column indexj1
- Final column index- Returns:
- A(i0:i1,j0:j1)
- Throws:
ArrayIndexOutOfBoundsException
- Submatrix indices
-
getMatrix
Get a submatrix.- Parameters:
r
- Array of row indices.c
- Array of column indices.- Returns:
- A(r(:),c(:))
- Throws:
ArrayIndexOutOfBoundsException
- Submatrix indices
-
getMatrix
Get a submatrix.- Parameters:
i0
- Initial row indexi1
- Final row indexc
- Array of column indices.- Returns:
- A(i0:i1,c(:))
- Throws:
ArrayIndexOutOfBoundsException
- Submatrix indices
-
getMatrix
Get a submatrix.- Parameters:
r
- Array of row indices.j0
- Initial column indexj1
- Final column index- Returns:
- A(r(:),j0:j1)
- Throws:
ArrayIndexOutOfBoundsException
- Submatrix indices
-
set
public void set(int i, int j, double s) Set a single element.- Parameters:
i
- Row index.j
- Column index.s
- A(i,j).- Throws:
ArrayIndexOutOfBoundsException
-
setMatrix
Set a submatrix.- Parameters:
i0
- Initial row indexi1
- Final row indexj0
- Initial column indexj1
- Final column indexX
- A(i0:i1,j0:j1)- Throws:
ArrayIndexOutOfBoundsException
- Submatrix indices
-
setMatrix
Set a submatrix.- Parameters:
r
- Array of row indices.c
- Array of column indices.X
- A(r(:),c(:))- Throws:
ArrayIndexOutOfBoundsException
- Submatrix indices
-
setMatrix
Set a submatrix.- Parameters:
r
- Array of row indices.j0
- Initial column indexj1
- Final column indexX
- A(r(:),j0:j1)- Throws:
ArrayIndexOutOfBoundsException
- Submatrix indices
-
setMatrix
Set a submatrix.- Parameters:
i0
- Initial row indexi1
- Final row indexc
- Array of column indices.X
- A(i0:i1,c(:))- Throws:
ArrayIndexOutOfBoundsException
- Submatrix indices
-
isSymmetric
public boolean isSymmetric()Returns true if the matrix is symmetric. (FracPete: taken from old weka.core.Matrix class)- Returns:
- boolean true if matrix is symmetric.
-
isSquare
public boolean isSquare()returns whether the matrix is a square matrix or not.- Returns:
- true if the matrix is a square matrix
-
transpose
Matrix transpose.- Returns:
- A'
-
norm1
public double norm1()One norm- Returns:
- maximum column sum.
-
norm2
public double norm2()Two norm- Returns:
- maximum singular value.
-
normInf
public double normInf()Infinity norm- Returns:
- maximum row sum.
-
normF
public double normF()Frobenius norm- Returns:
- sqrt of sum of squares of all elements.
-
uminus
Unary minus- Returns:
- -A
-
plus
C = A + B- Parameters:
B
- another matrix- Returns:
- A + B
-
plusEquals
A = A + B- Parameters:
B
- another matrix- Returns:
- A + B
-
minus
C = A - B- Parameters:
B
- another matrix- Returns:
- A - B
-
minusEquals
A = A - B- Parameters:
B
- another matrix- Returns:
- A - B
-
arrayTimes
Element-by-element multiplication, C = A.*B- Parameters:
B
- another matrix- Returns:
- A.*B
-
arrayTimesEquals
Element-by-element multiplication in place, A = A.*B- Parameters:
B
- another matrix- Returns:
- A.*B
-
arrayRightDivide
Element-by-element right division, C = A./B- Parameters:
B
- another matrix- Returns:
- A./B
-
arrayRightDivideEquals
Element-by-element right division in place, A = A./B- Parameters:
B
- another matrix- Returns:
- A./B
-
arrayLeftDivide
Element-by-element left division, C = A.\B- Parameters:
B
- another matrix- Returns:
- A.\B
-
arrayLeftDivideEquals
Element-by-element left division in place, A = A.\B- Parameters:
B
- another matrix- Returns:
- A.\B
-
times
Multiply a matrix by a scalar, C = s*A- Parameters:
s
- scalar- Returns:
- s*A
-
timesEquals
Multiply a matrix by a scalar in place, A = s*A- Parameters:
s
- scalar- Returns:
- replace A by s*A
-
times
Linear algebraic matrix multiplication, A * B- Parameters:
B
- another matrix- Returns:
- Matrix product, A * B
- Throws:
IllegalArgumentException
- Matrix inner dimensions must agree.
-
lu
LU Decomposition- Returns:
- LUDecomposition
- See Also:
-
qr
QR Decomposition- Returns:
- QRDecomposition
- See Also:
-
chol
Cholesky Decomposition- Returns:
- CholeskyDecomposition
- See Also:
-
svd
Singular Value Decomposition- Returns:
- SingularValueDecomposition
- See Also:
-
eig
Eigenvalue Decomposition- Returns:
- EigenvalueDecomposition
- See Also:
-
solve
Solve A*X = B- Parameters:
B
- right hand side- Returns:
- solution if A is square, least squares solution otherwise
-
solveTranspose
Solve X*A = B, which is also A'*X' = B'- Parameters:
B
- right hand side- Returns:
- solution if A is square, least squares solution otherwise.
-
inverse
Matrix inverse or pseudoinverse- Returns:
- inverse(A) if A is square, pseudoinverse otherwise.
-
sqrt
returns the square root of the matrix, i.e., X from the equation X*X = A.
Steps in the Calculation (seesqrtm
in Matlab):
- perform eigenvalue decomposition
[V,D]=eig(A) - take the square root of all elements in D (only the ones with positive
sign are considered for further computation)
S=sqrt(D) - calculate the root
X=V*S/V, which can be also written as X=(V'\(V*S)')'
-
X = 5 -4 1 0 0 -4 6 -4 1 0 1 -4 6 -4 1 0 1 -4 6 -4 0 0 1 -4 5 sqrt(X) = 2 -1 -0 -0 -0 -1 2 -1 0 -0 0 -1 2 -1 0 -0 0 -1 2 -1 -0 -0 -0 -1 2 Matrix m = new Matrix(new double[][]{{5,-4,1,0,0},{-4,6,-4,1,0},{1,-4,6,-4,1},{0,1,-4,6,-4},{0,0,1,-4,5}});
-
X = 7 10 15 22 sqrt(X) = 1.5667 1.7408 2.6112 4.1779 Matrix m = new Matrix(new double[][]{{7, 10},{15, 22}});
- Returns:
- sqrt(A)
- perform eigenvalue decomposition
-
regression
Performs a (ridged) linear regression. (FracPete: taken from old weka.core.Matrix class)- Parameters:
y
- the dependent variable vectorridge
- the ridge parameter- Returns:
- the coefficients
- Throws:
IllegalArgumentException
- if not successful
-
regression
Performs a weighted (ridged) linear regression. (FracPete: taken from old weka.core.Matrix class)- Parameters:
y
- the dependent variable vectorw
- the array of data point weightsridge
- the ridge parameter- Returns:
- the coefficients
- Throws:
IllegalArgumentException
- if the wrong number of weights were provided.
-
det
public double det()Matrix determinant- Returns:
- determinant
-
rank
public int rank()Matrix rank- Returns:
- effective numerical rank, obtained from SVD.
-
cond
public double cond()Matrix condition (2 norm)- Returns:
- ratio of largest to smallest singular value.
-
trace
public double trace()Matrix trace.- Returns:
- sum of the diagonal elements.
-
random
Generate matrix with random elements- Parameters:
m
- Number of rows.n
- Number of colums.- Returns:
- An m-by-n matrix with uniformly distributed random elements.
-
identity
Generate identity matrix- Parameters:
m
- Number of rows.n
- Number of colums.- Returns:
- An m-by-n matrix with ones on the diagonal and zeros elsewhere.
-
print
public void print(int w, int d) Print the matrix to stdout. Line the elements up in columns with a Fortran-like 'Fw.d' style format.- Parameters:
w
- Column width.d
- Number of digits after the decimal.
-
print
Print the matrix to the output stream. Line the elements up in columns with a Fortran-like 'Fw.d' style format.- Parameters:
output
- Output stream.w
- Column width.d
- Number of digits after the decimal.
-
print
Print the matrix to stdout. Line the elements up in columns. Use the format object, and right justify within columns of width characters. Note that is the matrix is to be read back in, you probably will want to use a NumberFormat that is set to US Locale.- Parameters:
format
- A Formatting object for individual elements.width
- Field width for each column.- See Also:
-
print
Print the matrix to the output stream. Line the elements up in columns. Use the format object, and right justify within columns of width characters. Note that is the matrix is to be read back in, you probably will want to use a NumberFormat that is set to US Locale.- Parameters:
output
- the output stream.format
- A formatting object to format the matrix elementswidth
- Column width.- See Also:
-
read
Read a matrix from a stream. The format is the same the print method, so printed matrices can be read back in (provided they were printed using US Locale). Elements are separated by whitespace, all the elements for each row appear on a single line, the last row is followed by a blank line. Note: This format differs from the one that can be read via the Matrix(Reader) constructor! For that format, the write(Writer) method is used (from the original weka.core.Matrix class).- Parameters:
input
- the input stream.- Throws:
IOException
- See Also:
-
write
Writes out a matrix. The format can be read via the Matrix(Reader) constructor. (FracPete: taken from old weka.core.Matrix class)- Parameters:
w
- the output Writer- Throws:
Exception
- if an error occurs- See Also:
-
toString
Converts a matrix to a string. (FracPete: taken from old weka.core.Matrix class) -
toMatlab
converts the Matrix into a single line Matlab string: matrix is enclosed by parentheses, rows are separated by semicolon and single cells by blanks, e.g., [1 2; 3 4].- Returns:
- the matrix in Matlab single line format
-
parseMatlab
creates a matrix from the given Matlab string.- Parameters:
matlab
- the matrix in matlab format- Returns:
- the matrix represented by the given string
- Throws:
Exception
- See Also:
-
getRevision
Returns the revision string.- Specified by:
getRevision
in interfaceRevisionHandler
- Returns:
- the revision
-
main
Main method for testing this class.
-