Class BaseMatrix<M extends BaseMatrix<M>>
- All Implemented Interfaces:
IArchive
- Direct Known Subclasses:
GenericMatrix
,Rmxn
,SquareMatrix
Class BaseMatrix
. This is a base class for objects representing
real-number matrix objects. Thus it contains basic matrix operations where
the interacting objects are all of type M
, or vectors of the
singular type V
. The template parameter M
is the
type of the child class. This mechanism allows
BaseMatrix<M extends BaseMatrix<M>>
to recognize the
type of it derived classes in order to create and process new objects as
necessary.
The objective of this base class is to hide the internal implementation of matrix operations from the child classes and all developers using the matrix packages.
Currently the internal matrix operations are supported by the EJML matrix package.
- Since:
- Oct 11, 2013
- Author:
- Christopher K. Allen, Blaz Kranjc
-
Field Summary
FieldsModifier and TypeFieldDescriptionstatic final String
Attribute marker for data managed by IArchive interfaceprotected static final double
A small number used in comparing matrix elements (e.g., #isEqual() )protected static final int
number of Units in the Last Place (ULPs) used for bracketing approximately equal values -
Constructor Summary
ConstructorsModifierConstructorDescriptionprotected
BaseMatrix
(double[][] arrVals) Initializing constructor for bases classBaseMatrix
.protected
BaseMatrix
(int cntRows, int cntCols) Creates a new, uninitialized instance of a square matrix with the given matrix dimensions.protected
BaseMatrix
(int cntRows, int cntCols, String strTokens) Parsing Constructor - creates an instance of the child class and initialize it according to a token string of element values.protected
BaseMatrix
(M matParent) Copy constructor forBaseMatrix
.protected
BaseMatrix
(org.ejml.data.DenseMatrix64F matrix) Initializing constructor for classBaseMatrix
. -
Method Summary
Modifier and TypeMethodDescriptionvoid
Assign this matrix to be the identity matrix.protected void
assignMatrix
(org.ejml.data.DenseMatrix64F matValue) Sets the internal matrix value to that given in the argument.void
Assign this matrix to be the zero matrix, specifically the matrix containing all 0's.abstract M
clone()
Base classes must override the clone operation in order to make deep copies of the current object.double
Ratio of the largest singular value over the smallest singular value.copy()
Create a deep copy of the this matrix object.boolean
Checks absolute equivalency.double[][]
Returns a copy of the internal Java array containing the matrix elements.int
Returns the number of columns in this matrix.double
getElem
(int i, int j) Return matrix element value.double
Returns the matrix element at the position indicated by the given row and column index sources.protected org.ejml.data.DenseMatrix64F
Return the internal matrix representation.int
Returns the number of rows in this matrix.int
hashCode()
"Borrowed" implementation from AffineTransform, since it is based on double attribute values.inverse()
Inverse of the matrix if the matrix is square, if the matrix is not square this is a pseudo-inverse.boolean
isApproxEqual
(M matTest) Tests whether the given matrix is approximately equal to this matrix.boolean
isApproxEqual
(M matTest, int cntUlp) Tests whether the given matrix is approximately equal to this matrix.boolean
isEquivalentTo
(BaseMatrix<M> matTest) Checks if the given matrix is algebraically equivalent to this matrix.boolean
isSquare()
Check if matrix is a square matrix.void
load
(DataAdaptor daptArchive) Restore the value of the this matrix from the contents of a data archive.double
max()
Return the maximum absolute value of all matrix elements.Non-destructive matrix subtraction.void
minusEquals
(M mat) In-place matrix subtraction.protected abstract M
newInstance
(int row, int col) Creates a new, uninitialized instance of this matrix type.protected M
newInstance
(org.ejml.data.DenseMatrix64F impInit) Creates a new instance of this matrix type initialized to the given implementation matrix.double
norm1()
The matrix norm || · ||1 induced from the l1 vector norm on Rn.double
norm2()
Returns the l2 induced norm of this matrix, which is the maximum, which turns out to be the spectral radius of the matrix.double
normF()
Return the Frobenius norm ||A||F .double
normInf()
The matrix norm || · ||∞ induced from the l∞ vector norm on Rn.Non-destructive matrix addition.void
plusEquals
(M mat) In-place matrix addition.void
print
(PrintWriter os) Print out the contents of the matrix in text format.int
rank()
Calculates the rank of the matrix.void
save
(DataAdaptor daptArchive) Save the value of this matrix to a data sink represented by theDataAdaptor
interface.void
setElem
(int i, int j, double s) Element assignment - assigns matrix element to the specified valuevoid
Set the element specified by the given position indices to the given new value.void
setMatrix
(double[][] arrMatrix) Sets the entire matrix to the values given in the Java primitive type double array.void
Parsing assignment - set the matrix according to a token string of element values.void
setSubMatrix
(int i0, int i1, int j0, int j1, double[][] arrSub) Set a block sub-matrix within the current matrix.times
(double s) Non-destructive scalar multiplication.Non-destructive matrix multiplication.<V extends BaseVector<V>>
Vtimes
(V vecFac) Non-destructive matrix-vector multiplication.void
timesEquals
(double s) In-place scalar multiplication.toString()
Convert the contents of the matrix to a string representation.Returns a string representation of this matrix.Returns a string representation of this matrix.toStringMatrix
(NumberFormat fmt, int intColWd) Returns a string representation of this matrix.Non-destructive transpose of this matrix.
-
Field Details
-
ATTR_DATA
Attribute marker for data managed by IArchive interface- See Also:
-
DBL_EPS
protected static final double DBL_EPSA small number used in comparing matrix elements (e.g., #isEqual() )- See Also:
-
ULPS_BRACKET
protected static final int ULPS_BRACKETnumber of Units in the Last Place (ULPs) used for bracketing approximately equal values- See Also:
-
-
Constructor Details
-
BaseMatrix
protected BaseMatrix(int cntRows, int cntCols) Creates a new, uninitialized instance of a square matrix with the given matrix dimensions. The matrix contains all zeros.- Parameters:
cntRows
- the matrix row count of this objectcntCols
- the matrix column count- Throws:
UnsupportedOperationException
- child class has not defined a public, zero-argument constructor
-
BaseMatrix
Copy constructor forBaseMatrix
. Creates a deep copy of the given object. The dimensions are set and the internal array is cloned.- Parameters:
matParent
- the matrix to be cloned- Since:
- Sep 25, 2013
-
BaseMatrix
Parsing Constructor - creates an instance of the child class and initialize it according to a token string of element values.
The token string argument is assumed to be one-dimensional and packed by column (ala FORTRAN).
- Parameters:
cntRows
- the matrix row size of this objectcntCols
- the matrix column size of this objectstrTokens
- token vector of getSize()^2 numeric values- Throws:
NumberFormatException
- bad number format, unparseable
-
BaseMatrix
protected BaseMatrix(double[][] arrVals) Initializing constructor for bases class
BaseMatrix
. Sets the entire matrix to the values given in the Java primitive type double array. The argument itself remains unchanged.The dimensions of the given Java double array determine the size of the matrix. An mxn Java double array creates an mxn
BaseMatrix
array. If the argument is not fully allocated or inconsistent, an exception is thrown.As an example consider the following Java array
double[][] arrInternal = new double[][] { {1.1, 1.2, 1.3, 1.4, 1.5}, {2.1, 2.2, 2.3, 2.0, 2.5}, {3.1, 3.2, 3.3, 3.4, 3.0} };
arrInternal
will be changed by the the encapsulating matrix object so should no longer be referenced after presenting it to this constructor.- Parameters:
arrVals
- Java primitive array to be new internal matrix value representation- Throws:
IllegalArgumentException
- the argument is degenerate and cannot represent a matrix- Since:
- Oct 4, 2013 by Christopher K. Allen
-
BaseMatrix
protected BaseMatrix(org.ejml.data.DenseMatrix64F matrix) Initializing constructor for classBaseMatrix
. Sets the internal matrix to the copy of the argument.- Parameters:
matrix
- implementation object to copy to this matrix
-
-
Method Details
-
clone
Base classes must override the clone operation in order to make deep copies of the current object. This operation cannot be done without the exact type. -
setElem
Element assignment - assigns matrix element to the specified value- Parameters:
i
- row indexj
- column index- Throws:
ArrayIndexOutOfBoundsException
- an index was equal to or larger than the matrix size
-
setElem
Set the element specified by the given position indices to the given new value.- Parameters:
iRow
- matrix row locationiCol
- matrix column indexdblVal
- matrix element at given row and column will be set to this value
-
setSubMatrix
public void setSubMatrix(int i0, int i1, int j0, int j1, double[][] arrSub) Set a block sub-matrix within the current matrix. If the given two-dimensional array is larger than block described by the indices it is truncated. If the given indices describe a matrix larger than the given two-dimensional array then an exception is thrown.- Parameters:
i0
- row index of upper left blocki1
- row index of lower right blockj0
- column index of upper left blockj1
- column index of lower right blockarrSub
- two-dimensional sub element array
-
setMatrix
Sets the entire matrix to the values given in the Java primitive type double array.- Parameters:
arrMatrix
- Java primitive array containing new matrix values- Throws:
ArrayIndexOutOfBoundsException
- the argument must have the same dimensions as this matrix
-
setMatrix
Parsing assignment - set the matrix according to a token string of element values. The token string argument is assumed to be one-dimensional and packed by column (aka FORTRAN).- Parameters:
strValues
- token vector of SIZE2 numeric values- Throws:
NumberFormatException
- bad number format, unparseableIllegalArgumentException
- wrong number of token strings
-
getRowCnt
public int getRowCnt()Returns the number of rows in this matrix. Specifically, if this matrix, denoted M, is in Rm×n, then the returned value is m.- Returns:
- the first dimension in the shape of this matrix.
- Since:
- Oct 14, 2013
-
getColCnt
public int getColCnt()Returns the number of columns in this matrix. Specifically, if this matrix, denoted M, is in Rm×n, then the returned value is n.- Returns:
- the second dimension in the shape of this matrix.
- Since:
- Oct 14, 2013
-
getElem
Return matrix element value. Get matrix element value at specified position.- Parameters:
i
- row indexj
- column index- Throws:
ArrayIndexOutOfBoundsException
- an index was equal to or larger than the matrix size
-
getElem
Returns the matrix element at the position indicated by the given row and column index sources.
NOTES
· It is expected that the object exposing the
IIndex
interface is an enumeration class restricting the number of possible index values.
· Consequently we do not declare a thrown exception assuming that that enumeration class eliminates the possibility of an out of bounds error.- Parameters:
indRow
- source of the row indexindCol
- source of the column index- Returns:
- value of the matrix element at the given row and column
- Since:
- Sep 30, 2013
-
getArrayCopy
public double[][] getArrayCopy()Returns a copy of the internal Java array containing the matrix elements. The array dimensions are given by the size of this matrix.- Returns:
- copied array of matrix values
-
isApproxEqual
Tests whether the given matrix is approximately equal to this matrix. The idea is that we ignore any numerical noise when comparing if the two matrices are equal.
This is a convenience class for the method
where the number of ULPs is set toisApproxEqual(BaseMatrix,int)
ULPS_BRACKET
.The matrices are compared element by element using
.ElementaryFunction.approxEq(double, double)
- Returns:
true
if the given matrix is equal to this one with the given number of significant digits,false
otherwise.- Since:
- Jul 22, 2015 by Christopher K. Allen
-
isApproxEqual
Tests whether the given matrix is approximately equal to this matrix. The idea is that we ignore any numerical noise when comparing if the two matrices are equal. This is done by ignoring the number of Units in the Last Place in the machine representation. The larger this number the more least significant digits we ignore.
The matrices are compared element by element using
.ElementaryFunction.approxEq(double, double, int)
- Parameters:
matTest
- the matrix being compared to this one.cntUlp
- number of Units in the Last Place to ignore- Returns:
true
if the given matrix is equal to this one with the given number of significant digits,false
otherwise.- Since:
- Jul 22, 2015 by Christopher K. Allen
-
copy
Create a deep copy of the this matrix object. The returned object is completely decoupled from the original.- Returns:
- a deep copy object of this matrix
-
assignZero
public void assignZero()Assign this matrix to be the zero matrix, specifically the matrix containing all 0's.- Since:
- Oct 3, 2013
-
assignIdentity
public void assignIdentity()Assign this matrix to be the identity matrix. The identity matrix is a matrix with 1's on the diagonal and 0's everywhere else. -
isEquivalentTo
Checks if the given matrix is algebraically equivalent to this matrix. That is, it is equal in size and element values.- Parameters:
matTest
- matrix under equivalency test- Returns:
true
if the argument is equivalent to this matrix,false
if otherwise- Since:
- Oct 1, 2013
-
isSquare
public boolean isSquare()Check if matrix is a square matrix.- Returns:
- true if matrix is square.
-
rank
public int rank()Calculates the rank of the matrix.- Returns:
- Rank of the matrix
-
conditionNumber
public double conditionNumber()Ratio of the largest singular value over the smallest singular value. Note that this method does a singular value decomposition just to get the number (done in the (wasteful) EJML internal implementation). Thus, this computation is not cheap if the matrix is large.- Returns:
- the ratio of extreme singular values
- Since:
- Oct 16, 2013
-
transpose
Non-destructive transpose of this matrix.- Returns:
- transposed copy of this matrix or
null
if error
-
inverse
Inverse of the matrix if the matrix is square, if the matrix is not square this is a pseudo-inverse.- Returns:
- inverse or pseudo-inverse of the matrix.
-
plus
Non-destructive matrix addition. This matrix is unaffected.- Parameters:
matAddend
- matrix to be added to this- Returns:
- the result of this matrix plus the given matrix (element-wise),
or
null
if error
-
plusEquals
In-place matrix addition. The given matrix is added to this matrix algebraically (element by element).- Parameters:
mat
- matrix to be added to this (no new objects are created)
-
minus
Non-destructive matrix subtraction. This matrix is unaffected.- Parameters:
matSub
- the subtrahend- Returns:
- the value of this matrix minus the value of the given matrix, or
null
if an error occurred
-
minusEquals
In-place matrix subtraction. The given matrix is subtracted from the value of this matrix. No additional objects are created.- Parameters:
mat
- subtrahend
-
times
Non-destructive scalar multiplication. This matrix is unaffected.- Parameters:
s
- multiplier- Returns:
- new matrix equal to the element-wise product of s and
this matrix, or
null
if an error occurred
-
timesEquals
public void timesEquals(double s) In-place scalar multiplication. Each element of this matrix is replaced by its product with the argument.- Parameters:
s
- multiplier
-
times
Non-destructive matrix multiplication. A new matrix is returned with the product while both multiplier and multiplicand are unchanged.- Parameters:
matRight
- multiplicand - right operand of matrix multiplication operator- Returns:
- new matrix which is the matrix product of this matrix and the
argument, or
null
if an error occurred
-
times
Non-destructive matrix-vector multiplication. The returned value is the usual product of the given vector pre-multiplied by this matrix. Specifically, denote by A this matrix and by x the argument vector, then the components {yi} of the returned vector y are given by
yi = Σj Aijxj- Parameters:
vecFac
- the vector factor- Returns:
- the matrix-vector product of this matrix with the argument
-
max
public double max()Return the maximum absolute value of all matrix elements. This can be considered a norm on matrices, but it is not sub-multiplicative. That is,
||AB||max is not necessarily bound by ||A||max ||B||max .
- Returns:
- maxi,j | Ai,j |
-
norm1
public double norm1()The matrix norm || · ||1 induced from the l1 vector norm on Rn. That is,
||A||1 ≡ maxx∈Rn ||Ax||1
where, by context, the second occurrence of ||·||1 is the Lesbeque 1-norm on Rn.NOTES:
· For square matrices induced norms are sub-multiplicative, that is ||AB|| ≤ ||A|| ||B||.
· The ||·||1 induced norm equates to the the maximum absolute column sum.- Returns:
- ||M||1 = maxi Σj |Mi,j|
-
norm2
public double norm2()Returns the l2 induced norm of this matrix, which is the maximum, which turns out to be the spectral radius of the matrix. Specifically,
||A||2 ≡ [ max λ(ATA) ]1/2 ,
= max ρ(A) ,
where λ(·) is the eigenvalue operator and ρ(·) is the singular value operator.- Returns:
- the maximum singular value of this matrix
-
normInf
public double normInf()The matrix norm || · ||∞ induced from the l∞ vector norm on Rn. That is,
||A||∞ ≡ maxx∈Rn ||Ax||∞
where, by context, the second occurrence of ||·||∞ is the Lesbeque ∞-norm on Rn.NOTES:
· For square matrices induced norms are sub-multiplicative, that is ||AB|| ≤ ||A|| ||B||.
· The ||·||∞ induced norm equates to the the maximum absolute column sum.- Returns:
- ||M||1 = maxi Σj |Mi,j|
-
normF
public double normF()Return the Frobenius norm ||A||F . The Frobenius norm has the property that it is both the element-wise Lebesgue 2-norm the Schatten 2-norm. Thus we have
||A||F = [ Σi Σj Ai,j2 ]1/2 = [ Tr(ATA) ]1/2 = [ Σi σi2 ]1/2
where Tr is the trace operator and σi are the singular values of matrix A.NOTES
· Since the Schatten norms are sub-multiplicative, the Frobenius norm is sub-multiplicative.
· The Frobenius norm is invariant under rotations by elements of O(2) ⊂ Rn×n .- Returns:
- ||A||F = [ Σi,j Aij2 ]1/2
-
print
Print out the contents of the matrix in text format.- Parameters:
os
- output stream to receive text dump
-
save
Save the value of this matrix to a data sink represented by theDataAdaptor
interface. -
load
Restore the value of the this matrix from the contents of a data archive.- Specified by:
load
in interfaceIArchive
- Parameters:
daptArchive
- interface to data source- Throws:
DataFormatException
- malformed data- See Also:
-
equals
Checks absolute equivalency. That is, checks whether or not the argument is this object. -
toString
Convert the contents of the matrix to a string representation. The format is similar to that of Mathematica. Specifically,
{ {a b }{c d } } -
toStringMatrix
Returns a string representation of this matrix. The string contains multiple lines, one for each row of the matrix. Within each line the matrix entries are formatted. Thus, the string should resemble the usual matrix format when printed out.- Returns:
- multiple line formatted string containing matrix elements in matrix format
- Since:
- Feb 8, 2013
-
toStringMatrix
Returns a string representation of this matrix. The string contains multiple lines, one for each row of the matrix. Within each line the matrix entries are formatted according to the given number format. The default column width is used. The string should resemble the usual matrix format when printed out.- Parameters:
fmt
-NumberFormat
object containing output format for matrix entries- Returns:
- multiple line formatted string containing matrix elements in matrix format
- Since:
- Feb 8, 2013
-
toStringMatrix
Returns a string representation of this matrix. The string contains multiple lines, one for each row of the matrix. Within each line the matrix entries are formatted according to the given number format. The string should resemble the usual matrix format when printed out.- Parameters:
fmt
-NumberFormat
object containing output format for matrix entriesintColWd
- number of characters used for each column (padding is with spaces)- Returns:
- multiple line formatted string containing matrix elements in matrix format
- Since:
- Feb 8, 2013
-
hashCode
public int hashCode()"Borrowed" implementation from AffineTransform, since it is based on double attribute values. Must implement hashCode to be consistent with equals as specified by contract of hashCode inObject
. -
getMatrix
protected org.ejml.data.DenseMatrix64F getMatrix()Return the internal matrix representation.- Returns:
- the internal matrix implementation
-
assignMatrix
protected void assignMatrix(org.ejml.data.DenseMatrix64F matValue) Sets the internal matrix value to that given in the argument. This is a deep copy operation. Note that the complete matrix is copy, thus the dimensions and other parameters are assigned as well.- Parameters:
matValue
- internal implementation of matrix values- Since:
- Oct 1, 2013
-
newInstance
Creates a new, uninitialized instance of this matrix type.
NOTE: · This method was made abstract by Ivo List. Rather than use reflection to instantiate new objects, this function is now delegated to the concrete classes. This architecture is more robust and allows the compiler to do more error checking.
- Parameters:
row
- Number of rows.col
- Number of columns.- Returns:
- uninitialized matrix object of type
M
- Since:
- Oct 1, 2013
-
newInstance
Creates a new instance of this matrix type initialized to the given implementation matrix.- Parameters:
impInit
- implementation matrix containing initialization values- Returns:
- initialized matrix object of type
M
- Since:
- Oct 1, 2013
-