Class SimpleMatrix

All Implemented Interfaces:
Serializable, ConstMatrix<SimpleMatrix>

public class SimpleMatrix extends SimpleBase<SimpleMatrix>

SimpleMatrix is a wrapper around a primitive matrix type (for example, DMatrixRMaj or FMatrixSparseCSC) that provides an easy to use object oriented interface for performing matrix operations. It is designed to be more accessible to novice programmers and provide a way to rapidly code up solutions by simplifying memory management and providing easy to use functions.

Most functions in SimpleMatrix do not modify the original matrix. Instead they create a new SimpleMatrix instance which is modified and returned. This greatly simplifies memory management and writing of code in general. It also allows operations to be chained, as is shown below:

SimpleMatrix K = P.mult(H.transpose().mult(S.invert()));

Working with both a primitive matrix and SimpleMatrix in the same code base is easy. To access the internal Matrix in a SimpleMatrix simply call SimpleBase.getMatrix(). To turn a Matrix into a SimpleMatrix use wrap(org.ejml.data.Matrix). Not all operations in EJML are provided for SimpleMatrix, but can be accessed by extracting the internal matrix.

The object oriented approach used in SimpleMatrix was originally inspired by JAMA.

Extending

SimpleMatrix contains a list of narrowly focused functions for linear algebra. To harness the functionality for another application and to the number of functions it supports it is recommended that one extends SimpleBase instead. This way the returned matrix type's of SimpleMatrix functions will be of the appropriate types. See StatisticsMatrix inside of the examples directory.

If SimpleMatrix is extended then the protected function createMatrix(int, int, org.ejml.data.MatrixType) should be extended and return the child class. The results of SimpleMatrix operations will then be of the correct matrix type.

Performance

The disadvantage of using this class is that it is more resource intensive, since it creates a new matrix each time an operation is performed. This makes the JavaVM work harder and Java automatically initializes the matrix to be all zeros. Typically operations on small matrices or operations that have a runtime linear with the number of elements are the most affected. More computationally intensive operations have only a slight unnoticeable performance loss. MOST PEOPLE SHOULD NOT WORRY ABOUT THE SLIGHT LOSS IN PERFORMANCE.

It is hard to judge how significant the performance hit will be in general. Often the performance hit is insignificant since other parts of the application are more processor intensive or the bottle neck is a more computationally complex operation. The best approach is benchmark and then optimize the code.

Creating matrices

MethodDescription
SimpleMatrix(int, int, Class) Create a matrix filled with zeros with the specified internal type.
SimpleMatrix(int, int, MatrixType) Create a matrix filled with zeros with the specified internal matrix type.
SimpleMatrix(int, int) Create a matrix filled with zeros.
SimpleMatrix(int, int, boolean, double...) Create a matrix with the provided double values, in either row-major or column-major order.
SimpleMatrix(int, int, boolean, float...) Create a matrix with the provided float values, in either row-major or column-major order.
SimpleMatrix(double[][]) Create a matrix from a 2D double array.
SimpleMatrix(float[][]) Create a matrix from a 2D float array.
SimpleMatrix(double[]) Create a column vector from a 1D double array.
SimpleMatrix(float[]) Create a column vector from a 1D float array.
SimpleMatrix(Matrix) Create a matrix copying the provided Matrix.
SimpleMatrix(SimpleMatrix) Create a matrix copying the provided SimpleMatrix.
wrap(Matrix) Create a matrix wrapping the provided Matrix.
filled(int, int, double) Create a matrix filled with the specified value.
ones(int, int) Create a matrix filled with ones.
diag(double...) Create a diagonal matrix.
diag(Class, double...) Create a diagonal matrix with the specified internal type.
identity(int) Create an identity matrix.
identity(int, Class) Create an identity matrix with the specified internal type.
random(int, int) Create a random DMatrixRMaj with values drawn from a continuous uniform distribution on the unit interval.
random_DDRM(int, int, double, double, Random) Create a random DMatrixRMaj with values drawn from a continuous uniform distribution using the provided random number generator.
random_DDRM(int, int) Create a random DMatrixRMaj with values drawn from a continuous uniform distribution on the unit interval.
random_FDRM(int, int, float, float, Random) Create a random FMatrixRMaj with values drawn from a continuous uniform distribution using the provided random number generator.
random_FDRM(int, int) Create a random FMatrixRMaj with values drawn from a continuous uniform distribution on the unit interval.
random_ZDRM(int, int, double, double, Random) Create a random ZMatrixRMaj with values drawn from a continuous uniform distribution using the provided random number generator.
random_ZDRM(int, int) Create a random ZMatrixRMaj with values drawn from a continuous uniform distribution on the unit interval.
random_CDRM(int, int, float, float, Random) Create a random CMatrixRMaj with values drawn from a continuous uniform distribution using the provided random number generator.
random_CDRM(int, int) Create a random CMatrixRMaj with values drawn from a continuous uniform distribution on the unit interval.
randomNormal(SimpleMatrix, Random) Create a random vector drawn from a multivariate normal distribution with the specified covariance.
SimpleBase.createLike() Create a matrix with the same shape and internal type as this matrix.
SimpleBase.copy() Create a copy of this matrix.

Getting elements, rows and columns

MethodDescription
SimpleBase.get(int) Get the value of the ith entry in row-major order.
SimpleBase.get(int, int) Get the value of the i,jth entry.
SimpleBase.get(int, int, Complex_F64) Get the value of the i,jth entry as a complex number.
SimpleBase.getReal(int, int) Get the real component of the i,jth entry.
SimpleBase.getImaginary(int, int) Get the imaginary component of the i,jth entry.
ConstMatrix.getImag(int, int) Alias for SimpleBase.getImaginary(int, int)
SimpleBase.getRow(int) Get the ith row.
SimpleBase.getColumn(int) Get the jth column.
SimpleBase.extractVector(boolean, int) Extract the specified row or column vector.
SimpleBase.extractMatrix(int, int, int, int) Extract the specified submatrix.
SimpleBase.rows(int, int) Extract the specified rows.
SimpleBase.cols(int, int) Extract the specified columns.
SimpleBase.diag() Extract the matrix diagonal, or construct a diagonal matrix from a vector.

Setting elements, rows and columns

MethodDescription
SimpleBase.set(int, double) Set the value of the ith entry in row-major order.
SimpleBase.set(int, int, double) Set the value of the i,jth entry.
SimpleBase.set(int, int, Complex_F64) Set the value of the i,jth entry as a complex number.
SimpleBase.set(int, int, double, double) Set the real and imaginary components of the i,jth entry.
SimpleBase.setRow(int, ConstMatrix) Set the ith row.
SimpleBase.setRow(int, int, double...) Set the values in the ith row.
SimpleBase.setColumn(int, ConstMatrix) Set the jth column.
SimpleBase.setColumn(int, int, double...) Set the values in the jth column.
SimpleBase.setTo(SimpleBase) Set the elements of this matrix to be equal to elements from another matrix.
SimpleBase.insertIntoThis(int, int, SimpleBase) Insert values from another matrix, starting in position i,j.
SimpleBase.fill(double) Set all elements of this matrix to be equal to specified value.
SimpleBase.fillComplex(double, double) Set all elements of this matrix to be equal to specified complex value.
SimpleBase.zero() Set all elements of this matrix to zero.

Basic operations

MethodDescription
SimpleBase.plus(double) Add a scalar value.
SimpleBase.plusComplex(double, double) Add a complex scalar value.
SimpleBase.plus(ConstMatrix) Add another matrix.
SimpleBase.plus(double, ConstMatrix) Add another matrix, first applying the specified scale factor.
SimpleBase.minus(double) Subtract a scalar value.
SimpleBase.minusComplex(double, double) Subtract a complex scalar value.
SimpleBase.minus(ConstMatrix) Subtract another matrix.
SimpleBase.scale(double) Multiply by a scalar value.
SimpleBase.scaleComplex(double, double) Multiply by a complex scalar value.
SimpleBase.divide(double) Divide by a scalar value.
SimpleBase.mult(ConstMatrix) Multiply with another matrix.
SimpleBase.dot(ConstMatrix) Calculate the dot product with another vector.
SimpleBase.negative() Get the negative of each entry.
SimpleBase.real() Get the real component of each entry.
SimpleBase.imaginary() Get the imaginary component of each entry.
ConstMatrix.imag() Alias for SimpleBase.imaginary().
SimpleBase.magnitude() Get the imaginary component of each entry.
SimpleBase.transpose() Get the transpose.
SimpleBase.transposeConjugate() Get the conjugate transpose.
SimpleBase.equation(String, Object...) Perform an equation in place on the matrix.

Elementwise operations

MethodDescription
SimpleBase.elementMult(ConstMatrix) Perform element by element multiplication with another matrix.
SimpleBase.elementDiv(ConstMatrix) Perform element by element division with another matrix.
SimpleBase.elementPower(double) Raise each entry to the specified power.
SimpleBase.elementPower(ConstMatrix) Raise each entry to the corresponding power in another matrix.
SimpleBase.elementExp() Compute the exponent of each entry.
SimpleBase.elementLog() Compute the logarithm of each entry.
SimpleBase.elementOp(SimpleOperations.ElementOpReal) Apply the specified real-valued function to each entry.
SimpleBase.elementOp(SimpleOperations.ElementOpComplex) Apply the specified complex-valued function to each entry.

Aggregations

MethodDescription
SimpleBase.elementSum() Compute the sum of all elements of this matrix.
SimpleBase.elementSumComplex() Compute the sum of all elements of a complex matrix.
SimpleBase.elementMax() Compute the maximum of all elements of this matrix.
SimpleBase.elementMaxAbs() Compute the maximum absolute value of all elements of this matrix.
SimpleBase.elementMin() Compute the minimum of all elements of this matrix.
SimpleBase.elementMinAbs() Compute the minimum absolute value of all elements of this matrix.

Linear algebra

MethodDescription
SimpleBase.solve(ConstMatrix) Solve the equation Ax = b.
SimpleBase.conditionP2() Compute the matrix condition number.
SimpleBase.invert() Compute the matrix inverse.
SimpleBase.pseudoInverse() Compute the Moore-Penrose pseudo-inverse.
SimpleBase.determinant() Compute the determinant.
SimpleBase.determinantComplex() Compute the determinant of a complex matrix.
SimpleBase.trace() Compute the trace.
SimpleBase.traceComplex() Compute the trace of a complex matrix.
SimpleBase.normF() Compute the Frobenius norm.
SimpleBase.eig() Compute the eigenvalue decomposition.
SimpleBase.svd() Compute the singular value decomposition.
SimpleBase.svd(boolean) Compute the singular value decomposition in compact or full format.

Combining matrices

MethodDescription
SimpleBase.combine(int, int, ConstMatrix) Combine with another matrix.
SimpleBase.concatRows(ConstMatrix...) Concatenate vertically with one or more other matrices.
SimpleBase.concatColumns(ConstMatrix...) Concatenate horizontally with one or more other matrices.
SimpleBase.kron(ConstMatrix) Compute the Kronecker product with another matrix.

Matrix properties

MethodDescription
SimpleBase.getNumRows() Get the number of rows.
SimpleBase.getNumCols() Get the number of columns.
ConstMatrix.getNumElements() Get the number of elements.
SimpleBase.bits() Get the size of the internal array elements (32 or 64).
SimpleBase.isVector() Check if this matrix is a vector.
SimpleBase.isIdentical(ConstMatrix, double) Check if this matrix is the same as another matrix, up to the specified tolerance.
SimpleBase.hasUncountable() Check if any of the matrix elements are NaN or infinite.

Converting and reshaping

MethodDescription
SimpleBase.convertToComplex() Convert to a complex matrix.
SimpleBase.convertToDense() Convert to a dense matrix.
SimpleBase.convertToSparse() Convert to a sparse matrix.
SimpleBase.reshape(int, int) Change the number of rows and columns.

Accessing the internal matrix

MethodDescription
SimpleBase.getType() Get the type of the wrapped matrix.
SimpleBase.getMatrix() Get the wrapped matrix.
SimpleBase.getDDRM() Get the wrapped matrix as a DMatrixRMaj.
SimpleBase.getFDRM() Get the wrapped matrix as a FMatrixRMaj.
SimpleBase.getZDRM() Get the wrapped matrix as a ZMatrixRMaj.
SimpleBase.getCDRM() Get the wrapped matrix as a CMatrixRMaj.
SimpleBase.getDSCC() Get the wrapped matrix as a DMatrixSparseCSC.
SimpleBase.getFSCC() Get the wrapped matrix as a FMatrixSparseCSC.

Loading and saving

MethodDescription
SimpleBase.loadCSV(String) Load a matrix from a CSV file.
SimpleBase.saveToFileCSV(String) Save this matrix to a CSV file.
SimpleBase.saveToMatrixMarket(String) Save this matrix in matrix market format.

Miscellaneous

MethodDescription
SimpleBase.iterator(boolean, int, int, int, int) Create an iterator for traversing a submatrix.
SimpleBase.getIndex(int, int) Get the row-major index corresponding to i,j.
SimpleBase.isInBounds(int, int) Check if the indices i,j are in bounds.
SimpleBase.toString() Get the string representation of the matrix.
SimpleBase.toArray2() Convert the matrix to a 2D array of doubles.
SimpleBase.print() Print the matrix to standard out.
SimpleBase.print(String) Print the matrix to standard out using the specified floating point format.
SimpleBase.printDimensions() Print the number of rows and columns.
See Also:
  • Field Details

    • END

      public static final int END
      A simplified way to reference the last row or column in the matrix for some functions.
      See Also:
  • Constructor Details

    • SimpleMatrix

      public SimpleMatrix(int numRows, int numCols, boolean rowMajor, double... data)

      Creates a new matrix which has the same value as the matrix encoded in the provided array. The input matrix's format can either be row-major or column-major.

      Note that 'data' is a variable argument type, so either 1D arrays or a set of numbers can be passed in:
      SimpleMatrix a = new SimpleMatrix(2,2,true,new double[]{1,2,3,4});
      SimpleMatrix b = new SimpleMatrix(2,2,true,1,2,3,4);

      Both are equivalent.

      Parameters:
      numRows - The number of rows.
      numCols - The number of columns.
      rowMajor - If the array is encoded in a row-major or a column-major format.
      data - The formatted 1D array. Not modified.
      See Also:
    • SimpleMatrix

      public SimpleMatrix(int numRows, int numCols, boolean rowMajor, float... data)

      Creates a new matrix which has the same value as the matrix encoded in the provided array. The input matrix's format can either be row-major or column-major.

      Note that 'data' is a variable argument type, so either 1D arrays or a set of numbers can be passed in:
      SimpleMatrix a = new SimpleMatrix(2,2,true,new float[]{1,2,3,4});
      SimpleMatrix b = new SimpleMatrix(2,2,true,1,2,3,4);

      Both are equivalent.

      Parameters:
      numRows - The number of rows.
      numCols - The number of columns.
      rowMajor - If the array is encoded in a row-major or a column-major format.
      data - The formatted 1D array. Not modified.
      See Also:
    • SimpleMatrix

      public SimpleMatrix(double[][] data)

      Creates a matrix with the values and shape defined by the 2D array 'data'. It is assumed that 'data' has a row-major formatting:

      data[ row ][ column ]

      Parameters:
      data - 2D array representation of the matrix. Not modified.
      See Also:
    • SimpleMatrix

      public SimpleMatrix(float[][] data)

      Creates a matrix with the values and shape defined by the 2D array 'data'. It is assumed that 'data' has a row-major formatting:

      data[ row ][ column ]

      Parameters:
      data - 2D array representation of the matrix. Not modified.
      See Also:
    • SimpleMatrix

      public SimpleMatrix(double[] data)
      Creates a column vector with the values and shape defined by the 1D array 'data'.
      Parameters:
      data - 1D array representation of the vector. Not modified.
    • SimpleMatrix

      public SimpleMatrix(float[] data)
      Creates a column vector with the values and shape defined by the 1D array 'data'.
      Parameters:
      data - 1D array representation of the vector. Not modified.
    • SimpleMatrix

      public SimpleMatrix(int numRows, int numCols)
      Creates a new matrix that is initially set to zero with the specified dimensions. This will wrap a DMatrixRMaj.
      Parameters:
      numRows - The number of rows in the matrix.
      numCols - The number of columns in the matrix.
    • SimpleMatrix

      public SimpleMatrix(int numRows, int numCols, Class<?> type)
      Creates a new matrix that is initially set to zero with the specified dimensions and type.
      Parameters:
      numRows - The number of rows in the matrix.
      numCols - The number of columns in the matrix.
      type - The matrix type
    • SimpleMatrix

      public SimpleMatrix(int numRows, int numCols, MatrixType type)
      Creates a new matrix that is initially set to zero with the specified dimensions and matrix type.
      Parameters:
      numRows - The number of rows in the matrix.
      numCols - The number of columns in the matrix.
      type - The matrix type
    • SimpleMatrix

      public SimpleMatrix(SimpleMatrix orig)
      Creates a new SimpleMatrix which is identical to the original.
      Parameters:
      orig - The matrix which is to be copied. Not modified.
    • SimpleMatrix

      public SimpleMatrix(Matrix orig)
      Creates a new SimpleMatrix which is a copy of the Matrix.
      Parameters:
      orig - The original matrix whose value is copied. Not modified.
    • SimpleMatrix

      protected SimpleMatrix()
      Constructor for internal library use only. Nothing is configured and is intended for serialization.
  • Method Details

    • wrap

      public static SimpleMatrix wrap(Matrix internalMat)
      Creates a new SimpleMatrix with the specified Matrix used as its internal matrix. This means that the reference is saved and calls made to the returned SimpleMatrix will modify the passed in Matrix.
      Parameters:
      internalMat - The internal Matrix of the returned SimpleMatrix. Will be modified.
    • filled

      public static SimpleMatrix filled(int numRows, int numCols, double a)
      Creates a new matrix filled with the specified value. This will wrap a DMatrixRMaj.
      Parameters:
      numRows - The number of rows in the matrix.
      numCols - The number of columns in the matrix.
      a - The value to fill the matrix with.
      Returns:
      A matrix filled with the value a.
    • ones

      public static SimpleMatrix ones(int numRows, int numCols)
      Creates a new matrix filled with ones. This will wrap a DMatrixRMaj.
      Parameters:
      numRows - The number of rows in the matrix.
      numCols - The number of columns in the matrix.
      Returns:
      A matrix of ones.
    • identity

      public static SimpleMatrix identity(int width)
      Creates a new identity matrix with the specified size. This will wrap a DMatrixRMaj.
      Parameters:
      width - The width and height of the matrix.
      Returns:
      An identity matrix.
      See Also:
    • identity

      public static SimpleMatrix identity(int width, Class<?> type)
      Creates a new identity matrix with the specified size and type.
      Parameters:
      width - The width and height of the matrix.
      type - The matrix type
      Returns:
      An identity matrix.
    • diag

      public static SimpleMatrix diag(double... vals)

      Creates a matrix where all but the diagonal elements are zero. The values of the diagonal elements are specified by the parameter 'vals'. This will wrap a DMatrixRMaj.

      To extract the diagonal elements from a matrix see SimpleBase.diag().

      Parameters:
      vals - The values of the diagonal elements.
      Returns:
      A diagonal matrix.
      See Also:
    • diag

      public static SimpleMatrix diag(Class<?> type, double... vals)
      Creates a matrix where all but the diagonal elements are zero. The values of the diagonal elements are specified by the parameter 'vals'.
      Parameters:
      type - The matrix type
      vals - The values of the diagonal elements.
      Returns:
      A diagonal matrix.
    • random_DDRM

      public static SimpleMatrix random_DDRM(int numRows, int numCols, double minValue, double maxValue, Random rand)
      Creates a random matrix with values drawn from the continuous uniform distribution from minValue (inclusive) to maxValue (exclusive). This will wrap a DMatrixRMaj.
      Parameters:
      numRows - The number of rows in the new matrix
      numCols - The number of columns in the new matrix
      minValue - Lower bound
      maxValue - Upper bound
      rand - The random number generator that's used to fill the matrix.
      Returns:
      The new random matrix.
      See Also:
    • random

      public static SimpleMatrix random(int numRows, int numCols)
      Creates a random matrix with values drawn from the continuous uniform distribution from 0.0 (inclusive) to 1.0 (exclusive).
      Parameters:
      numRows - The number of rows in the new matrix
      numCols - The number of columns in the new matrix
      See Also:
    • random_DDRM

      public static SimpleMatrix random_DDRM(int numRows, int numCols)
      Creates a random matrix with values drawn from the continuous uniform distribution from 0.0 (inclusive) to 1.0 (exclusive). The random number generator is ThreadLocalRandom.current(). This will wrap a DMatrixRMaj.
      Parameters:
      numRows - The number of rows in the new matrix
      numCols - The number of columns in the new matrix
    • random_FDRM

      public static SimpleMatrix random_FDRM(int numRows, int numCols, float minValue, float maxValue, Random rand)
      Creates a random matrix with values drawn from the continuous uniform distribution from minValue (inclusive) to maxValue (exclusive). This will wrap a FMatrixRMaj.
      Parameters:
      numRows - The number of rows in the new matrix
      numCols - The number of columns in the new matrix
      minValue - Lower bound
      maxValue - Upper bound
      rand - The random number generator that's used to fill the matrix.
      Returns:
      The new random matrix.
      See Also:
    • random_FDRM

      public static SimpleMatrix random_FDRM(int numRows, int numCols)
      Creates a random matrix with values drawn from the continuous uniform distribution from 0.0 (inclusive) to 1.0 (exclusive). The random number generator is ThreadLocalRandom.current(). This will wrap a FMatrixRMaj.
      Parameters:
      numRows - The number of rows in the new matrix
      numCols - The number of columns in the new matrix
    • random_ZDRM

      public static SimpleMatrix random_ZDRM(int numRows, int numCols, double minValue, double maxValue, Random rand)
      Creates a random matrix with real and complex components drawn from the continuous uniform distribution from minValue (inclusive) to maxValue (exclusive). This will wrap a ZMatrixRMaj.
      Parameters:
      numRows - The number of rows in the new matrix
      numCols - The number of columns in the new matrix
      minValue - Lower bound
      maxValue - Upper bound
      rand - The random number generator that's used to fill the matrix.
      Returns:
      The new random matrix.
      See Also:
    • random_ZDRM

      public static SimpleMatrix random_ZDRM(int numRows, int numCols)
      Creates a random matrix with values drawn from the continuous uniform distribution from 0.0 (inclusive) to 1.0 (exclusive). The random number generator is ThreadLocalRandom.current(). This will wrap a ZMatrixRMaj.
      Parameters:
      numRows - The number of rows in the new matrix
      numCols - The number of columns in the new matrix
    • random_CDRM

      public static SimpleMatrix random_CDRM(int numRows, int numCols, float minValue, float maxValue, Random rand)
      Creates a random matrix with real and complex components drawn from the continuous uniform distribution from minValue (inclusive) to maxValue (exclusive). This will wrap a CMatrixRMaj.
      Parameters:
      numRows - The number of rows in the new matrix
      numCols - The number of columns in the new matrix
      minValue - Lower bound
      maxValue - Upper bound
      rand - The random number generator that's used to fill the matrix.
      Returns:
      The new random matrix.
      See Also:
    • random_CDRM

      public static SimpleMatrix random_CDRM(int numRows, int numCols)
      Creates a random matrix with values drawn from the continuous uniform distribution from 0.0 (inclusive) to 1.0 (exclusive). The random number generator is ThreadLocalRandom.current(). This will wrap a CMatrixRMaj.
      Parameters:
      numRows - The number of rows in the new matrix
      numCols - The number of columns in the new matrix
    • randomNormal

      public static SimpleMatrix randomNormal(SimpleMatrix covariance, Random random)

      Creates a new vector which is drawn from a multivariate normal distribution with zero mean and the provided covariance.

      Parameters:
      covariance - Covariance of the multivariate normal distribution
      random - The random number generator that's used to fill the matrix.
      Returns:
      Vector randomly drawn from the distribution
      See Also:
    • createMatrix

      protected SimpleMatrix createMatrix(int numRows, int numCols, MatrixType type)
      Description copied from class: SimpleBase
      Used internally for creating new instances of SimpleMatrix. If SimpleMatrix is extended by another class this function should be overridden so that the returned matrices are of the correct type.
      Specified by:
      createMatrix in class SimpleBase<SimpleMatrix>
      Parameters:
      numRows - number of rows in the new matrix.
      numCols - number of columns in the new matrix.
      type - Type of matrix it should create
      Returns:
      A new matrix.
    • wrapMatrix

      protected SimpleMatrix wrapMatrix(Matrix m)
      Specified by:
      wrapMatrix in class SimpleBase<SimpleMatrix>