cox.jmatt.java.MathTools
Class MMatrix

java.lang.Object
  extended by cox.jmatt.java.MathTools.MMatrix

public class MMatrix
extends java.lang.Object

MMatrix represents a mathematical matrix, a rectangular array of numbers. This class provides tools for creating and manipulating matrices, for doing arithmetic operations with and to them, and for presenting them nicely. The companion to this class is MMatrixBuilder, a class designed solely to create MMatrices from various styles of input data (many involving Strings!).

Once created, a MMatrix is immutable. None of its methods change it in any way, nor are any of its critical parts subject to change, inadvertent or otherwise. The heart of a MMatrix is a double[][] array. This array is NEVER exposed directly! Any operation which might result in a change to the elements of the matrix returns either a copy of the elements or a copy of the MMatrix with the required changes made.


Constructor Summary
MMatrix()
          Standard ScriptingObject constructor.
MMatrix(double[][] pAry)
          Method to create a MMatrix from a double[][] array.
MMatrix(MMatrix pMatrix)
          Copy constructor.
 
Method Summary
 MMatrix add(MMatrix pSummand)
          ADD this matrix to another.
 int columns()
          Return the number of columns in this MMatrix.
static MMatrix createMMatrix(java.lang.String pFormat)
          Create a MMatrix from a formatted String.
 double determinant()
          Calculate and return the determinant of a SQUARE matrix.
 double[][] elements()
          Get the elements in this MMatrix.
 double[] evaluate(java.lang.Number[] pVals)
          View the MMatrix as a system of equations and evaluate each equation (row) against the values given.
 double[] evaluate(java.lang.String pVarVals)
          Interpret the matrix as a system of equations and evaluate each row (equation) against the values given for each column (variable).
 java.lang.String format(double[] pRHVM, java.lang.String pRowSep, java.lang.String pColSep, java.lang.String[] pVars, java.lang.String[] pRels, java.lang.String pAugSep, java.lang.String pPrefix, java.lang.String pSuffix)
          Format this MMatrix.
 java.lang.String formatMatrix(java.lang.String pRowSep, java.lang.String pColSep, java.lang.String pPrefix, java.lang.String pSuffix)
          This method is a souped-up version of toString(String, String).
 double[][] getZero()
          Instance version of ZERO(), should it be required.
 MMatrix multiply(double pScalar)
          Multiply the elements in this MMatrix by a scalar constant.
 MMatrix multiply(MMatrix pFactor)
          MULTIPLY this matrix by another one.
 MMatrix newMMatrix(java.lang.String pFormat)
          Instance version of createMMatrix().
 java.lang.String order()
          Return the order of the MMatrix.
 int rows()
          Return the number of rows in this MMatrix.
static void setDefaultNumberFormat(java.text.NumberFormat pNFormat)
          Use this method to set the default NumberFormat for all subsequent MMatrix instances.
static void setLatexEnvironment(java.lang.String pEnv, boolean pColSpec, java.lang.String pOptions)
          Set the global LaTeX environment used to render the MMatrix.
 void setNewDefaultNumberFormat(java.text.NumberFormat pNFormat)
          Instance shadow to set default NumberFormat.
 void setNewLatexEnvironment(java.lang.String pEnv, boolean pColSpec, java.lang.String pOptions)
          Instance shadow to set LaTex environment.
 void setNumberFormat(java.text.NumberFormat pNFormat)
          Each MMatrix has an internal NumberFormat object.
 MMatrix setVariables(java.lang.String pVars)
          This is a system of equations method.
 MMatrix subtract(MMatrix pSubtrahend)
          SUBTRACT another matrix from this one.
 java.lang.String toLatex(double[] pRHVM, java.lang.String[] pVars, java.lang.String[] pRels)
          Print this MMatrix using LaTeX notation.
 java.lang.String toMathML()
          Convenience method with square braces for fences: toMathML('[', ']');.
 java.lang.String toMathML(java.lang.String pLFence, java.lang.String pRFence)
          Render this MMatrix as MathML.
 java.lang.String toString()
          This method calls toString(null, null) and wraps some extra text around the result.
 java.lang.String toString(java.lang.String pRowSep, java.lang.String pColSep)
          This method prints the MMatrix elements in one long string.
 java.lang.String toXML(java.lang.String pID)
          Print the MMatrix in simplified XML form.
 MMatrix transpose()
          Form and return the transpose of this MMatrix.
static double[][] ZERO()
          This is the zero matrix; the default return value for many error conditions.
 
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, wait, wait, wait
 

Constructor Detail

MMatrix

public MMatrix()
Standard ScriptingObject constructor.


MMatrix

public MMatrix(double[][] pAry)
Method to create a MMatrix from a double[][] array. This is the only true constructor for this class since the MMatrixBuilder class has plenty of parsing and construction methods.


MMatrix

public MMatrix(MMatrix pMatrix)
Copy constructor. It does NOT copy the variables set for the MMatrix being copied.

Method Detail

createMMatrix

public static MMatrix createMMatrix(java.lang.String pFormat)
Create a MMatrix from a formatted String. The row separator is a semicolon and the element separator is a comma. This is also the default toString() format.


newMMatrix

public MMatrix newMMatrix(java.lang.String pFormat)
Instance version of createMMatrix().


ZERO

public static final double[][] ZERO()
This is the zero matrix; the default return value for many error conditions. It consists of the double[][] '{{0}}'.


getZero

public double[][] getZero()
Instance version of ZERO(), should it be required.


rows

public int rows()
Return the number of rows in this MMatrix.


columns

public int columns()
Return the number of columns in this MMatrix.


elements

public double[][] elements()
Get the elements in this MMatrix. A copy of the actual elements array is returned!


order

public java.lang.String order()
Return the order of the MMatrix. This will be a String of the form 'RxC' where R is the rows and C is the columns.


add

public MMatrix add(MMatrix pSummand)
ADD this matrix to another. If the orders are different the zero MMatrix is returned; no exception is thrown. If the other MMatrix is null, a copy of this is returned.


subtract

public MMatrix subtract(MMatrix pSubtrahend)
SUBTRACT another matrix from this one. If the orders are different the zero MMatrix is returned; no exception is thrown. If the other MMatrix is null, a copy of this one is returned.


multiply

public MMatrix multiply(MMatrix pFactor)
MULTIPLY this matrix by another one. If the these columns are different from pFactor's rows, the zero MMatrix is returned; no exception is thrown. If the other MMatrix is null, a copy of this one is returned.


multiply

public MMatrix multiply(double pScalar)
Multiply the elements in this MMatrix by a scalar constant. The original matrix is not changed; a copy with the products is returned.

Parameters:
pScalar - The scalar value to multiply by each element in the matrix.
Returns:
A copy of this MMatrix with the multiplications done.

determinant

public double determinant()
Calculate and return the determinant of a SQUARE matrix. This is done recursively by minors with no shortcutting. WARNING: This method is brittle!! If the matrix is not square, if any row or column is not defined or any other error occurs the return value is Double.NaN.


transpose

public MMatrix transpose()
Form and return the transpose of this MMatrix. Columns become rows and rows become columns.


toString

public java.lang.String toString(java.lang.String pRowSep,
                                 java.lang.String pColSep)
This method prints the MMatrix elements in one long string. The row- and column- separators can be specified. The default values are a semicolon for the row separator and a comma for the column separator.


toXML

public java.lang.String toXML(java.lang.String pID)
Print the MMatrix in simplified XML form. This is an empty <MMatrix> tag with the attribute 'data='. The data string uses a semicolon for the row separator and a comma for the column separator. If the ID parameter is not blank or null, it appears as an 'id=' attribute.

Parameters:
pID - String ID for the XML tag. Ignored if null or empty.

toString

public java.lang.String toString()
This method calls toString(null, null) and wraps some extra text around the result.

Overrides:
toString in class java.lang.Object

setVariables

public MMatrix setVariables(java.lang.String pVars)
This is a system of equations method. It sets the variables to be used when the system is printed. The variables used can be changed as they are not a part of the actual matrix represented by the MMatrix. If there are fewer columns than variables any extras are ignored. If there are fewer variables than columns, the variables are padded with 'x#' where '#' is the column number. A null or empty String sets each variable to its default value.

Parameters:
pVars - A String of space-separated values representing the variables for the system.
Returns:
A reference to this MMatrix.

evaluate

public double[] evaluate(java.lang.String pVarVals)
Interpret the matrix as a system of equations and evaluate each row (equation) against the values given for each column (variable). The values for the variables are given as a space-separated String of numbers. If there are more columns than values the array is padded with zeros. If there are more values than variables, the leftovers are ignored. Any errors generated during parsing are reported at Debug level.


evaluate

public double[] evaluate(java.lang.Number[] pVals)
View the MMatrix as a system of equations and evaluate each equation (row) against the values given. The variable values are given as type Number to allow an array of Integer or Double.


format

public java.lang.String format(double[] pRHVM,
                               java.lang.String pRowSep,
                               java.lang.String pColSep,
                               java.lang.String[] pVars,
                               java.lang.String[] pRels,
                               java.lang.String pAugSep,
                               java.lang.String pPrefix,
                               java.lang.String pSuffix)

Format this MMatrix. This is the formatting uber-method; it can format as a plain matrix, an augmented matrix or a system of equations. The parameters provide full control over every aspect of the process.

Plain Matrix

To format as a plain matrix pass null for the constants matrix (pRHVM), the variables, the relations and the augmentation separator. This leaves only the row and column separators along with the prefix and suffix, which are valid for all options. If pPrefix and pSuffix are null they are ignored. If pRowSep is null its default is a semicolon. If pColSep is null it defaults to a comma. No other value-detection is performed so whitespace characters can be used.

Augmented Matrix

To format as an augmented matrix pass a non-null augmentation separator and make sure pRHVM is not null or empty. If so then no constants will appear. If pRHVM has more elements than the matrix has rows any leftovers are ignored; and if it has too few then rows past the end will have no constants. The row separator does appear at the end of each row, after the augmentation value, and the column separator appears between the coefficient elements but not between the last coefficient and the augmentation separator or value.

System of Equations

To format a system of equations or inequalities at least one of 'pVars' or 'pRels' must be non-null. The constant array (pRHVM) should also be defined and contain sufficient elements; see 'Augmented Matrix' for details. If there are not enough relations for the number of rows the shortfall defaults to equality ('=') and if there are too many the extras are ignored. Likewise with the variable names; the default values are 'x0,' 'x1' and so on.

Augmented Matrix and Systems of Equations Notes

If all argument values are specified and not null then priority goes to System of Equations. In all cases the column and row separators are used; for systems of equations it is appended after the variable and before the sign of the next term. The row separator is appended to the end of every row except the last row. The prefix and suffix Strings, if present, appear absolutely first and absolutely last, respectively.

This method makes no assumptions about the correctness of the constants passed in; it does not evaluate the numbers, it simply formats them. This allows for construction of inconsistent or dependent systems BUT, as just stated, no mathematical error-checking is performed!

This method deprecates all Question-valued formatting methods. These methods will be removed by stable version 1.5 or 1.6.

Parameters:
pRHVM - The constants matrix augmented onto the coefficient matrix.
pRowSep - The row separator String. Defaults to a semicolon if null.
pColSep - The column separator. Defaults to a comma if null.
pVars - The variables to use when formatting as a system.
pRels - The relations to use when formatting as a system.
pAugSep - The separator between the last coefficient and the augmented constant. Defaults to a blank if null.
pPrefix - String value prepended to the output String, once. Ignored if null.
pSuffix - String appended to the end of the output, once. Ignored if null.

formatMatrix

public java.lang.String formatMatrix(java.lang.String pRowSep,
                                     java.lang.String pColSep,
                                     java.lang.String pPrefix,
                                     java.lang.String pSuffix)
This method is a souped-up version of toString(String, String). It allows for the inclusion of a prefix- and suffix-String and it formats the numbers in the element array.

Parameters:
pRowSep - The row separator. Defaults to a newline.
pColSep - The column separator. Defaults to a single space.
pPrefix - The prefix, which appears ONCE and first. Ignored if null or empty.
pSuffix - The suffix tacked on at the end. Ignored if empty or null.
Returns:
The MMatrix formatted as a String.

setNumberFormat

public void setNumberFormat(java.text.NumberFormat pNFormat)
Each MMatrix has an internal NumberFormat object. If not null it is applied to the numbers in ALL format__() methods. Use this method to set the NumberFormat for this MMatrix.

Parameters:
pNFormat - A NumberFormat to use when formatting matrices. Set to null to switch it off.

setDefaultNumberFormat

public static void setDefaultNumberFormat(java.text.NumberFormat pNFormat)
Use this method to set the default NumberFormat for all subsequent MMatrix instances. Setting null clears it.


setNewDefaultNumberFormat

public void setNewDefaultNumberFormat(java.text.NumberFormat pNFormat)
Instance shadow to set default NumberFormat.


toMathML

public java.lang.String toMathML(java.lang.String pLFence,
                                 java.lang.String pRFence)
Render this MMatrix as MathML. The pLFence and pRFence elements are parsed but should only contain a fence character. If either fence character is null or empty it is not added.

Parameters:
pLFence - The left fence character.
pRFence - The right fence character.
Returns:
A MathML-formatted MMatrix.

toMathML

public java.lang.String toMathML()
Convenience method with square braces for fences: toMathML('[', ']');.


setLatexEnvironment

public static void setLatexEnvironment(java.lang.String pEnv,
                                       boolean pColSpec,
                                       java.lang.String pOptions)

Set the global LaTeX environment used to render the MMatrix. These settings are global and once set remain in effect until changed. The default LaTeX environment used with the '/begin{}' statement is 'tabular' and setting pEnv to null restores this.

The 'pColSpec' parameter determines whether or not column alignment specifications are appended to the end of the '/begin{}' statement. This is true by default but can be changed. The 'pOptions' parameter is for any square-bracket options between '/begin' and the opening curly brace. If this String is defined it will be included verbatim otherwise it is ignored. By default it is null.

To summarize, the parameter placement is:

/begin[options]{environment}{colSpec}

Parameters:
pEnv - The LaTeX environment used to format the MMatrix. Defaults to 'tabular.'
pColSpec - true to include the column alignment specification (default), false to omit it.
pOptions - LaTeX 'square bracket' options. Ignored if null.

setNewLatexEnvironment

public void setNewLatexEnvironment(java.lang.String pEnv,
                                   boolean pColSpec,
                                   java.lang.String pOptions)
Instance shadow to set LaTex environment.


toLatex

public java.lang.String toLatex(double[] pRHVM,
                                java.lang.String[] pVars,
                                java.lang.String[] pRels)

Print this MMatrix using LaTeX notation. Parameters are per the format() method. The Row/Column separators are handled internally as is the Augmentation separator. The prefix and suffix Strings are set to the appropriate LaTeX /begin{} and /end{} statements. All LaTeX configuration settings are global and are set with the setLatexEnvironment() methods.

LaTeX-ing MMatrices

(N.B. When discussing LaTeX statements here the forward slash ('/') is used in place of the backslash to avoid ISSUES.)

This method contains the most sophisiticated LaTeX processing of all the core tools. It is designed to output LaTeX markup for a plain matrix, an augmented matrix or a system of equations. As stated above it makes use of the standard format() method with LaTeX-specific values provided for the required arguments. Since LaTeX allows quite a few options these values can be configured via the setLatexEnvironment() methods.

By default the environment used is 'tabular' with column-alignment specification enabled and no (square-bracket) options. These are easily changed but, once set, remain at the set values until they are reset! It is also possible through clever use of the 'environment' parameter to include a second 'curly-brace' structure after the environment. Simply disable column alignment, put a closing curly brace after the environment name, an opening curly brace and whatever is desired within the second pair. This method automatically closes the last curly brace.

The machinery here uses a least common denominator approach: it supplies the bare minimum LaTeX to allow for maximum flexibility. It supplies the 'begin... \end' block with the settings detailed above but nothing else. Specifically it doesn't apply any fence characters so these should be included in the Question format.

Respectively the arguments are the right-side constant matrix (as a double[] array), the variables to be used for a system of equations and the relations used in the system of equations, both of the latter as String[] arrays. Alignment characters can be included with the variables or the relations in order to control system-of-equations alignment more precisely. Exactly what is formatted depends on the arguments. More specifically, it depends on which ones are defined and which are not.

If all three arguments are null the method prints a plain matrix. If the constant matrix is non-null and both other arguments are null the result is an augmented matrix. The '|c' IS added if the column specifier is enabled so the vertical line is supplied. If the first argument is non-null and either of the other two is non-null a system of equations is attempted. In order for this attempt to succeed the environment must be changed to 'eqnarray' or something equivalent and the column alignment specifier must be disabled. For systems of equations (or inequalities!) both the second and third arguments should be specified; however, the default relation for this method is '&=&'.

IMPORTANT NOTES: In order to format an augmented matrix both the second and third arguments MUST be null. For either an augmented matrix or a system the first argument must be non-null. For a system of equations the environment MUST be changed! If fancier formatting options or more granular control is desired the plain format() method must be used.

Parameters:
pRHVM - The constant matrix for augmented matrices or systems. Must be non-null for either.
pVars - The variables used when formatting a system of equations. If non-null a system is attempted.
pRels - The relations used when formatting a system. If non-null this is attempted.