comirva.audio.util.math
Class Matrix

java.lang.Object
  extended by comirva.audio.util.math.Matrix
All Implemented Interfaces:
XMLSerializable, Serializable, Cloneable

public class Matrix
extends Object
implements Cloneable, XMLSerializable, Serializable

Jama = Java Matrix class.

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:

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();

See Also:
Serialized Form

Constructor Summary
Matrix(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 array
Matrix(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.
Matrix(Vector<double[]> rows, boolean clone)
          Construct a matrix from a Vector of double[]
 
Method Summary
 Matrix abs()
          returns a new Matrix object, where each value is set to the absolute value
 Matrix arrayLeftDivide(Matrix B)
          Element-by-element left division, C = A.
 Matrix arrayLeftDivideEquals(Matrix B)
          Element-by-element left division in place, A = A.
 Matrix arrayRightDivide(Matrix B)
          Element-by-element right division, C = A.
 Matrix arrayRightDivideEquals(Matrix B)
          Element-by-element right division in place, A = A.
 Matrix arrayTimes(Matrix B)
          Element-by-element multiplication, C = A.
 Matrix arrayTimesEquals(Matrix B)
          Element-by-element multiplication in place, A = A.
 CholeskyDecomposition chol()
          Cholesky Decomposition
 Object clone()
          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.
 Matrix copy()
          Make a deep copy of a matrix
 Matrix cov()
          Calculate the full covariance matrix.
 double det()
          Matrix determinant
 void diffEquals()
          X.diffEquals() calculates differences between adjacent columns of this matrix.
 EigenvalueDecomposition eig()
          Eigenvalue Decomposition
 double get(int i, int j)
          Get a single element.
 double[][] getArray()
          Access the internal two-dimensional array.
 double[][] getArrayCopy()
          Copy the internal two-dimensional array.
 int getColumnDimension()
          Get column dimension.
 double[] getColumnPackedCopy()
          Make a one-dimensional column packed copy of the internal array.
 Matrix getMatrix(int[] r, int[] c)
          Get a submatrix.
 Matrix getMatrix(int[] r, int j0, int j1)
          Get a submatrix.
 Matrix getMatrix(int i0, int i1, int[] c)
          Get a submatrix.
 Matrix getMatrix(int i0, int i1, int j0, int j1)
          Get a submatrix.
 int getRowDimension()
          Get row dimension.
 double[] getRowPackedCopy()
          Make a one-dimensional row packed copy of the internal array.
static Matrix identity(int m, int n)
          Generate identity matrix
 Matrix inverse()
          Matrix inverse or pseudoinverse
 void logEquals()
          X.logEquals() calculates the natural logarithem of each element of the matrix.
 LUDecomposition lu()
          LU Decomposition
 Matrix mean(int dim)
          Returns the mean values along the specified dimension.
 Matrix minus(Matrix B)
          C = A - B
 Matrix minusEquals(Matrix B)
          A = A - B
 double norm1()
          One norm
 double norm2()
          Two norm
 double normF()
          Frobenius norm
 double normInf()
          Infinity norm
 Matrix plus(Matrix B)
          C = A + B
 Matrix plusEquals(Matrix B)
          A = A + B
 Matrix pow(double exp)
          X.powEquals() calculates the power of each element of the matrix.
 void powEquals(double exp)
          X.powEquals() calculates the power of each element of the matrix.
 void print(int w, int d)
          Print the matrix to stdout.
 void print(NumberFormat format, int width)
          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.
 QRDecomposition qr()
          QR Decomposition
static Matrix random(int m, int n)
          Generate matrix with random elements
 int rank()
          Matrix rank
 void read(InputStream in)
           
static Matrix readCSV(InputStream inputStream)
           
 void readXML(XMLStreamReader parser)
          Reads the xml representation of an object form the xml input stream.
 void set(int i, int j, double s)
          Set a single element.
 void setMatrix(int[] r, int[] c, Matrix X)
          Set a submatrix.
 void setMatrix(int[] r, int j0, int j1, Matrix X)
          Set a submatrix.
 void setMatrix(int i0, int i1, int[] c, Matrix X)
          Set a submatrix.
 void setMatrix(int i0, int i1, int j0, int j1, Matrix X)
          Set a submatrix.
 Matrix solve(Matrix B)
          Solve A*X = B
 Matrix solveTranspose(Matrix B)
          Solve X*A = B, which is also A'*X' = B'
 double sum()
          Returns the sum of the component of the matrix.
 SingularValueDecomposition svd()
          Singular Value Decomposition
 void thrunkAtLowerBoundary(double value)
          X.thrunkAtLowerBoundariy().
 Matrix times(double s)
          Multiply a matrix by a scalar, C = s*A
 Matrix times(Matrix B)
          Linear algebraic matrix multiplication, A * B
 Matrix timesEquals(double s)
          Multiply a matrix by a scalar in place, A = s*A
 Matrix timesTriangular(Matrix B)
          Linear algebraic matrix multiplication, A * B B being a triangular matrix Note: Actually the matrix should be a column orienten, upper triangular matrix but use the row oriented, lower triangular matrix instead (transposed), because this is faster due to the easyer array access.
 double trace()
          Matrix trace.
 Matrix transpose()
          Matrix transpose.
 Matrix uminus()
          Unary minus
 void write(OutputStream out)
           
 void writeAscii(String filename)
          Writes the Matrix to an ascii-textfile that can be read by Matlab.
 void writeXML(XMLStreamWriter writer)
          Writes the xml representation of this object to the xml ouput stream.
 
Methods inherited from class java.lang.Object
equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait
 

Constructor Detail

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:
constructWithCopy(double[][])

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

public Matrix(Vector<double[]> rows,
              boolean clone)
Construct a matrix from a Vector of double[]

Parameters:
rows - A Vector containing double[] items. Each double[] item is a row of the matrix to create. All double[] items must be of the same length.
Method Detail

constructWithCopy

public static Matrix constructWithCopy(double[][] A)
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

public Matrix copy()
Make a deep copy of a matrix


clone

public Object clone()
Clone the Matrix object.

Overrides:
clone in class 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

public Matrix getMatrix(int i0,
                        int i1,
                        int j0,
                        int j1)
Get a submatrix.

Parameters:
i0 - Initial row index
i1 - Final row index
j0 - Initial column index
j1 - Final column index
Returns:
A(i0:i1,j0:j1)
Throws:
ArrayIndexOutOfBoundsException - Submatrix indices

getMatrix

public Matrix getMatrix(int[] r,
                        int[] c)
Get a submatrix.

Parameters:
r - Array of row indices.
c - Array of column indices.
Returns:
A(r(:),c(:))
Throws:
ArrayIndexOutOfBoundsException - Submatrix indices

getMatrix

public Matrix getMatrix(int i0,
                        int i1,
                        int[] c)
Get a submatrix.

Parameters:
i0 - Initial row index
i1 - Final row index
c - Array of column indices.
Returns:
A(i0:i1,c(:))
Throws:
ArrayIndexOutOfBoundsException - Submatrix indices

getMatrix

public Matrix getMatrix(int[] r,
                        int j0,
                        int j1)
Get a submatrix.

Parameters:
r - Array of row indices.
j0 - Initial column index
j1 - 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

public void setMatrix(int i0,
                      int i1,
                      int j0,
                      int j1,
                      Matrix X)
Set a submatrix.

Parameters:
i0 - Initial row index
i1 - Final row index
j0 - Initial column index
j1 - Final column index
X - A(i0:i1,j0:j1)
Throws:
ArrayIndexOutOfBoundsException - Submatrix indices

setMatrix

public void setMatrix(int[] r,
                      int[] c,
                      Matrix X)
Set a submatrix.

Parameters:
r - Array of row indices.
c - Array of column indices.
X - A(r(:),c(:))
Throws:
ArrayIndexOutOfBoundsException - Submatrix indices

setMatrix

public void setMatrix(int[] r,
                      int j0,
                      int j1,
                      Matrix X)
Set a submatrix.

Parameters:
r - Array of row indices.
j0 - Initial column index
j1 - Final column index
X - A(r(:),j0:j1)
Throws:
ArrayIndexOutOfBoundsException - Submatrix indices

setMatrix

public void setMatrix(int i0,
                      int i1,
                      int[] c,
                      Matrix X)
Set a submatrix.

Parameters:
i0 - Initial row index
i1 - Final row index
c - Array of column indices.
X - A(i0:i1,c(:))
Throws:
ArrayIndexOutOfBoundsException - Submatrix indices

transpose

public 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

public Matrix uminus()
Unary minus

Returns:
-A

plus

public Matrix plus(Matrix B)
C = A + B

Parameters:
B - another matrix
Returns:
A + B

plusEquals

public Matrix plusEquals(Matrix B)
A = A + B

Parameters:
B - another matrix
Returns:
A + B

minus

public Matrix minus(Matrix B)
C = A - B

Parameters:
B - another matrix
Returns:
A - B

minusEquals

public Matrix minusEquals(Matrix B)
A = A - B

Parameters:
B - another matrix
Returns:
A - B

arrayTimes

public Matrix arrayTimes(Matrix B)
Element-by-element multiplication, C = A.*B

Parameters:
B - another matrix
Returns:
A.*B

arrayTimesEquals

public Matrix arrayTimesEquals(Matrix B)
Element-by-element multiplication in place, A = A.*B

Parameters:
B - another matrix
Returns:
A.*B

arrayRightDivide

public Matrix arrayRightDivide(Matrix B)
Element-by-element right division, C = A./B

Parameters:
B - another matrix
Returns:
A./B

arrayRightDivideEquals

public Matrix arrayRightDivideEquals(Matrix B)
Element-by-element right division in place, A = A./B

Parameters:
B - another matrix
Returns:
A./B

arrayLeftDivide

public Matrix arrayLeftDivide(Matrix B)
Element-by-element left division, C = A.\B

Parameters:
B - another matrix
Returns:
A.\B

arrayLeftDivideEquals

public Matrix arrayLeftDivideEquals(Matrix B)
Element-by-element left division in place, A = A.\B

Parameters:
B - another matrix
Returns:
A.\B

times

public Matrix times(double s)
Multiply a matrix by a scalar, C = s*A

Parameters:
s - scalar
Returns:
s*A

timesEquals

public Matrix timesEquals(double s)
Multiply a matrix by a scalar in place, A = s*A

Parameters:
s - scalar
Returns:
replace A by s*A

times

public Matrix times(Matrix B)
Linear algebraic matrix multiplication, A * B

Parameters:
B - another matrix
Returns:
Matrix product, A * B
Throws:
IllegalArgumentException - Matrix inner dimensions must agree.

timesTriangular

public Matrix timesTriangular(Matrix B)
Linear algebraic matrix multiplication, A * B B being a triangular matrix Note: Actually the matrix should be a column orienten, upper triangular matrix but use the row oriented, lower triangular matrix instead (transposed), because this is faster due to the easyer array access.

Parameters:
B - another matrix
Returns:
Matrix product, A * B
Throws:
IllegalArgumentException - Matrix inner dimensions must agree.

diffEquals

public void diffEquals()
X.diffEquals() calculates differences between adjacent columns of this matrix. Consequently the size of the matrix is reduced by one. The result is stored in this matrix object again.


logEquals

public void logEquals()
X.logEquals() calculates the natural logarithem of each element of the matrix. The result is stored in this matrix object again.


powEquals

public void powEquals(double exp)
X.powEquals() calculates the power of each element of the matrix. The result is stored in this matrix object again.


pow

public Matrix pow(double exp)
X.powEquals() calculates the power of each element of the matrix.

Returns:
Matrix

thrunkAtLowerBoundary

public void thrunkAtLowerBoundary(double value)
X.thrunkAtLowerBoundariy(). All values smaller than the given one are set to this lower boundary.


lu

public LUDecomposition lu()
LU Decomposition

Returns:
LUDecomposition
See Also:
LUDecomposition

qr

public QRDecomposition qr()
QR Decomposition

Returns:
QRDecomposition
See Also:
QRDecomposition

chol

public CholeskyDecomposition chol()
Cholesky Decomposition

Returns:
CholeskyDecomposition
See Also:
CholeskyDecomposition

svd

public SingularValueDecomposition svd()
Singular Value Decomposition

Returns:
SingularValueDecomposition
See Also:
SingularValueDecomposition

eig

public EigenvalueDecomposition eig()
Eigenvalue Decomposition

Returns:
EigenvalueDecomposition
See Also:
EigenvalueDecomposition

solve

public Matrix solve(Matrix B)
Solve A*X = B

Parameters:
B - right hand side
Returns:
solution if A is square, least squares solution otherwise

solveTranspose

public Matrix solveTranspose(Matrix B)
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

public Matrix inverse()
Matrix inverse or pseudoinverse

Returns:
inverse(A) if A is square, pseudoinverse otherwise.

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

public static Matrix random(int m,
                            int n)
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

public static Matrix identity(int m,
                              int n)
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

public void print(PrintWriter output,
                  int w,
                  int d)
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

public void print(NumberFormat format,
                  int width)
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:
DecimalFormat.setDecimalFormatSymbols(java.text.DecimalFormatSymbols)

print

public void print(PrintWriter output,
                  NumberFormat format,
                  int width)
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 elements
width - Column width.
See Also:
DecimalFormat.setDecimalFormatSymbols(java.text.DecimalFormatSymbols)

write

public void write(OutputStream out)
           throws IOException
Throws:
IOException

readCSV

public static Matrix readCSV(InputStream inputStream)
                      throws IOException
Throws:
IOException

read

public void read(InputStream in)
          throws IOException
Throws:
IOException

writeXML

public void writeXML(XMLStreamWriter writer)
              throws IOException,
                     XMLStreamException
Writes the xml representation of this object to the xml ouput stream.

There is the convetion, that each call to a writeXML() method results in one xml element in the output stream.

Specified by:
writeXML in interface XMLSerializable
Parameters:
writer - XMLStreamWriter the xml output stream
Throws:
IOException - raised, if there are any io troubles
XMLStreamException - raised, if there are any parsing errors

readXML

public void readXML(XMLStreamReader parser)
             throws IOException,
                    XMLStreamException
Reads the xml representation of an object form the xml input stream.

There is the convention, that readXML() starts parsing by checking the start tag of this object and finishes parsing by checking the end tag. The caller has to ensure, that at method entry the current token is the start tag. After the method call it's the callers responsibility to move from the end tag to the next token.

Specified by:
readXML in interface XMLSerializable
Parameters:
parser - XMLStreamReader the xml input stream
Throws:
IOException - raised, if there are any io troubles
XMLStreamException - raised, if there are any parsing errors

mean

public Matrix mean(int dim)
Returns the mean values along the specified dimension.

Parameters:
dim - If 1, then the mean of each column is returned in a row vector. If 2, then the mean of each row is returned in a column vector.
Returns:
A vector containing the mean values along the specified dimension.

cov

public Matrix cov()
Calculate the full covariance matrix.

Returns:
the covariance matrix

sum

public double sum()
Returns the sum of the component of the matrix.

Returns:
the sum

abs

public Matrix abs()
returns a new Matrix object, where each value is set to the absolute value

Returns:
a new Matrix with all values being positive

writeAscii

public void writeAscii(String filename)
                throws IllegalArgumentException
Writes the Matrix to an ascii-textfile that can be read by Matlab. Usage in Matlab: load('filename', '-ascii');

Parameters:
filename - the name of the ascii file to create, e.g. "C:\\temp\\matrix.ascii"
Throws:
IllegalArgumentException - if there is a problem with the filename