Matrix Class
Navigation: PGMs > Classes > Predefined Classes
Species Database Class  Particle Size Definition Class  Array Class  StrArray Class  Matrix Class  Tag Select Class  Plant Model Class  Noise Class  TimeClass 

Contents
Description
The MATRIX class provides member functions, to create a dynamic matrix and manipulate its elements.
 The user may read in a matrix from a text file.
 The user may set constant values into a matrix when it is declared.
 Various Matrix Algebra functions are available.
Notes:
 The initial length (rows and columns) of the matrix is zero.
 The matrix is zero indexed, i.e. the index starts at zero.
 If the index is out of range (0 <= index < length) then a runtime "PGM class execution error" will occur and the MATRIX operation will be ignored.
 If the user reads values into a matrix from a CSV file, the file may contain alphanumeric strings, but the alphanumeric strings must NOT contain any spaces.
Data Members
None
Member Functions
The example in the table below is based on the following variables and matrix declarations.
Matrix a, b, c, L, M, M1, M2，I, Iv1, CIv1 Real d, Qty, Det Long RowCount, ColCount Bit OK, EqualOK, MultMatrixOK, MultArrayOK, InvertOK, SolveOK Array TestRow, TestCol, xA, X
Note that a number of the functions below return a bit to indicate whether they have been performed successfully or not. The use of this bit is optional. For example, the statement M.Load("$Prj\MyData.txt") will read a text file of data into the matrix M. If the statement is written as OK = M.Load("$Prj\MyData.txt"), the text file will be written into M as before and the bit variable OK will be set to 1 if the operation was successful or 0 if it was not. There is usually no other message to indicate if an operation has failed.
Call  Functionality  Return Type  Parameters  Example 
SetSize(Rows,Columns)  The matrix size is set to rows x columns.  Rows : the required number of rows of the matrix, is of data type LONG. Columns : the required number of columns of the matrix, is of data type LONG. 
a.SetSize(5, 3)  
GetRowCount()  This returns the current number of rows of the matrix.  Long  None  RowCount = a.GetRowCount() 
GetColCount()  This returns the current number of columns of the matrix.  Long  None  ColCount = a.GetColCount() 
SetIdentity(size) Implemented in Build 138 
The matrix is set as an identity matrix of the specified size.  size : the required number of rows/columns of the matrix, is of data type LONG. The identity matrix is a square matrix with diagonal having values of 1 and everything else zero. 
I.SetIdentity(3)
This will return a matrix \begin{bmatrix} 1 & 0 & 0 \\ 0 & 1 & 0 \\ 0 & 0 & 1 \end{bmatrix}  
SetAll(value)  This sets all the elements of the array to the specified value.  value : the required initialising value. This is of data type REAL.  a.SetAll(0)  
SetAt(Rowindex, ColumnIndex, value)  This sets the element of the matrix, which corresponds to the given indexes to the specified value.  RowIndex : the index of the required Row entry in the matrix (Note: index starts at zero). This is of data type LONG. ColumnIndex: the index of the required Column entry in the matrix (Note: index starts at zero). This is of data type LONG. 
a.SetAt(2, 2, 2.2)  
GetAt(RowIndex, ColumnIndex)  This retrieves the value of the element of the matrix, which corresponds to the given indexes.  Real  RowIndex: the index of the required Row entry in the matrix (Note: index starts at zero). This is of data type LONG. ColumnIndex: the index of the required Column entry in the matrix (Note: index starts at zero). This is of data type LONG. 
d = a.GetAt(3, 1) 
IncAt(RowIndex, ColumnIndex, value)  This sets the element of the matrix with the increased value.  RowIndex: the index of the required Row entry in the matrix (Note: index starts at zero). This is of data type LONG. ColumnIndex: the index of the required Column entry in the matrix (Note: index starts at zero). This is of data type LONG. 
a.IncAt(3, 2, Qty)  
DecAt(RowIndex, ColumnIndex, value)  This sets the element of the matrix with the decreased value.  RowIndex: the index of the required Row entry in the matrix (Note: index starts at zero). This is of data type LONG. ColumnIndex: the index of the required Column entry in the matrix (Note: index starts at zero). This is of data type LONG. 
a.DecAt(0, 2, Qty)  
Sum()  This calculates the sum of all elements in the matrix.  Real  None  d = a.Sum() 
Avg()  This calculates the average of all elements in the matrix.  Real  None  d = a.Avg() 
Min()  This returns the minimum value of all elements in the matrix.  Real  None  d = a.Min() 
Max()  This returns the maximum value of all elements in the matrix.  Real  None  d = a.Max() 
Load(filename) 
This creates a new matrix from a file.
Note: if any elements exist in the matrix, prior to calling Load, these elements will be overridden. 
Bit 
fileName : either the actual filename and path in quotations or a STR variable, which refers to the file. Use $Prj in the folder string for folders relative to the project folder. 
OK = b.Load("$Prj\Data.txt") 
Save(filename) 
This saves the matrix data to a comma separated text file.

Bit 
fileName : the actual filename and path in quotations or a STR variable, which refers to the file. Optionally use $Prj in the folder string for folders relative to the project folder. 
OK = a.Save("OutputData.csv") 
CopyToClipboard()  This saves the array data to the clipboard. The function returns the value, True.  Bit  None  a.CopyToClipboard() 
SetAll(value)  This sets all the elements of the Matrix to the specified value.  value : the required initialising value. This is of data type REAL.  a.SetAll(0)  
Scale(value) Implemented in Build137. 
All the elements of the Matrix are scaled by the specified value (New value = original value * Scale). 
value : the required scaling factor. This is of data type REAL.  a.Scale(2)  Each value of the Matrix "a" will be increased by factor of 2.  
Offset(value) Implemented in Build137. 
All the elements of the Matrix are offset by the specified value (New value = original value + Offset). 
value : the required offset value. This is of data type REAL.  a.Offset(5)  Each value of the Matrix "a" will be increased by 5.  
Copy(Matrix) Implemented in Build137. 
The Matrix is resized to be the same as the specified Matrix and all the elements are copied into the new Matrix. 
Matrix: the name of the Matrix to copy from. This is an Matrix class. 
PreVals.Copy(a)  
IsEqual(Matrix) Implemented in Build137. 
This compares the current Matrix with the specified Matrix data, if the matrix sizes match and each element of the Matrix are equal, the function returns the value, True.  Bit  Matrix: the name of the Matrix to compare with. This is a Matrix class.  EqualOK = PreVals.IsEqual(a)  Returns true if the size of "PreVals" and "a" are equal and the values in Matrix "PreVals" are equal to the values of the Matrix "a". 
GetRow(RowIndex, Array) Implemented in Build137. 
This retrieves the values the specified row of the matrix, the values are stored in the specified array. Array size is set to the number of columns. Return false if invalid RowIndex. 
Bit  RowIndex: the index of the required Row entry in the matrix (Note: index starts at zero). This is of data type LONG. Array: the name of the array to stored the retrieved information. This is an Array class. 
a.GetRow(0, TestRow) 
GetCol(ColIndex, Array) Implemented in Build137. 
This retrieves the values the specified column of the matrix, the values are stored in the specified array. Array size is set to the number of rows. Return false if invalid ColIndex. 
Bit  ColIndex: the index of the required column entry in the matrix (Note: index starts at zero). This is of data type LONG. Array: the name of the array to stored the retrieved information. This is an Array class. 
a.GetCol(0, TestCol) 
SetRow(RowIndex, Array) Implemented in Build137. 
This sets the values at the specified row in the matrix, with values from the specified array. The matrix row length must equal to the array length, otherwise it will report an error. Return false if invalid RowIndex or length of Array does not match number of columns. 
Bit  RowIndex: the index of the required Row entry in the matrix (Note: index starts at zero). This is of data type LONG. Array: the name of the array that contains the values. This is an Array class. 
a.SetRow(1, TestRow) 
SetCol(ColIndex, Array) Implemented in Build137. 
This sets the values at the specified column in the matrix, with values from the specified array. The matrix column length must equal to the array length, otherwise it will report an error. Return false if invalid ColIndex or length of Array does not match number of rows. 
Bit  ColIndex: the index of the required column entry in the matrix (Note: index starts at zero). This is of data type LONG. Array: the name of the array that contains the values. This is an Array class. 
a.SetCol(1, TestCol) 
Add(Matrix) Implemented in Build137. 
This function performs addition between current matrix and a specified matrix. New value for each element in current matrix = value in current Matrix + specified Matrix. The two Matrices must be the same size. If they are not the same size then return value is false, a runtime error is reported and current matrix values are left unchanged. 
Bit  Matrix: the name of the specified Matrix. This is a Matrix class.  OK = M.Add(M1) (each element in M = M + M1) 
Sub(Matrix) Implemented in Build137. 
This function performs subtraction between current matrix and a specified matrix. New value for each element in current matrix = value in current Matrix  specified Matrix. The two Matrices must be the same size. If they are not the same size then return value is false, a runtime error is reported and current matrix values are left unchanged. 
Bit  Matrix: the name of the specified Matrix. This is a Matrix class.  OK = M.Sub(M1) (each element in M = M  M1) 
Mult(Matrix) Implemented in Build137. 
This function performs multiplication between current matrix and a specified matrix. New value for each element in current matrix = value in current Matrix * specified Matrix. The two Matrices must be the same size. If they are not the same size then return value is false, a runtime error is reported and current matrix values are left unchanged. 
Bit  Matrix: the name of the specified Matrix. This is a Matrix class.  OK = M.Mult(M1) (each element in M = M * M1) 
Div(Matrix) Implemented in Build137. 
This function performs division between current matrix and a specified matrix. New value for each element in current matrix = value in current Matrix / specified Matrix. The two Matrices must be the same size. If they are not the same size then return value is false, a runtime error is reported and current matrix values are left unchanged. 
Bit  Matrix: the name of the specified Matrix. This is a Matrix class.  OK = M.Div(M1) (each element in M = M / M1) 
MultMatrix(Matrix) Implemented in Build137. 
Matrix multiplication for matrix of different size, but the number of Rows in the specified Matrix must match the number of columns of the current matrix. The resulting matrix is resized.  Bit  Matrix: the name of the specified Matrix. This is a Matrix class.  MultMatrixOK = L.MultMatrix(M1)  If Matrix "L" is 3x2 and Matrix "M1" is 2x4, resulting Matrix "L" is resized to 3x4. 
MultArray(Array) Implemented in Build137. 
Matrix by Array multiplication, the Array is treated as a matrix with one of the dimensions equal to 1. The matrix column length must match the array length.  Bit  Array: the name of the specified Array. This is an Array class.  MultArrayOK = L.MultArray(xA)  the number of columns in Matrix "L" must equal to the array length of "xA" 
Transpose() Implemented in Build137. 
Transposes the matrix.  M.Transpose()  
Determinant() Implemented in Build138. 
Calculates and returns determinant of the matrix. The matrix must be square, if not a Runtime error is given and the value of zero is returned. LU Decomposition method is used to calculate the Determinant. A result of zero indicates matrix is Singular and the matrix cannot be inverted.  Real  None  Det = I.Determinant() 
Invert() Implemented in Build138. 
Inverts the matrix. The matrix must be square, if not runtime error and "false" is returned. If unable to complete "invert" due to matrix is "Singular" (determinant = 0), returns "false" but still changes matrix values. 
Bit  None  InvertOK = Iv1.Invert() 
Solve(Array) Implemented in Build138.25617. 
Solves a system of equations. The matrix must be square and the length of the array must be same size of matrix, if not runtime error and "false" is returned. LU Decomposition and back substitution method is used. 
Bit  Array: the name of the specified RHS, which is overwritten. This is an Array class.  SolveOK = A.Solve(X) 
CopyAdd(Matrix1, Matrix2) Implemented in Build137. 
Makes a copy of the supplied Matrix1 and then calls Add(Matrix2). The two Matrices must be the same size, otherwise value remains unchanged and error is returned. 
Bit  Matrix1: the name of the first specified Matrix. This is a Matrix class. Matrix2: the name of the second specified Matrix. This is a Matrix class. 
OK = M.CopyAdd(M1, M2) (each element in M = M1 + M2) 
CopySub(Matrix1, Matrix2) Implemented in Build137. 
Makes a copy of the supplied Matrix1 and then calls Sub(Matrix2). The two Matrices must be the same size, otherwise value remains unchanged and error is returned. 
Bit  Matrix1: the name of the first specified Matrix. This is a Matrix class. Matrix2: the name of the second specified Matrix. This is a Matrix class. 
OK = M.CopySub(M1, M2) (each element in M = M1  M2) 
CopyMult(Matrix1, Matrix2) Implemented in Build137. 
Makes a copy of the supplied Matrix1 and then calls Mult(Matrix2). The two Matrices must be the same size, otherwise value remains unchanged and error is returned. 
Bit  Matrix1: the name of the first specified Matrix. This is a Matrix class. Matrix2: the name of the second specified Matrix. This is a Matrix class. 
OK = M.CopyMult(M1, M2) (each element in M = M1 * M2) 
CopyDiv(Matrix1, Matrix2) Implemented in Build137. 
Makes a copy of the supplied Matrix1 and then calls Div(Matrix2). The two Matrices must be the same size, otherwise value remains unchanged and error is returned. 
Bit  Matrix1: the name of the first specified Matrix. This is a Matrix class. Matrix2: the name of the second specified Matrix. This is a Matrix class. 
OK = M.CopyDiv(M1, M2) (each element in M = M1 / M2) 
CopyMultMatrix(Matrix1, Matrix2) Implemented in Build137. 
This function performs multiplication between two matrices and stores the values in a new matrix(current matrix). The matrices can be of different size, but the number of Rows in the specified Matrix must match the number of columns of the current matrix. The resulting matrix is resized.  Bit  Matrix1: the name of the first specified Matrix. This is a Matrix class. Matrix2: the name of the second specified Matrix. This is a Matrix class. 
MultMatrixOK = M.CopyMultMatrix(L,M1)  If Matrix "L" is 3x2 and Matrix "M1" is 2x4, resulting Matrix "M" is resized to 3x4. 
CopyMultArray(Matrix, Array) Implemented in Build137. 
This function performs multiplication between a matrix and an array. The results are stored in a new matrix(current matrix). Matrix by Array multiplication, the Array is treated as a matrix with one of the dimensions equal to 1. The matrix column length must match the array length.  Bit  Matrix: the name of the first specified Matrix. This is a Matrix class. Array: the name of the specified Array. This is an Array class. 
MultArrayOK = M.CopyMultArray(L,xA)  the number of columns in Matrix "L" must equal to the array length of "xA" 
CopyTranspose(Matrix) Implemented in Build138. 
Makes a copy of the supplied Matrix and then calls Transpose() so that original matrix is left unchanged.  Matrix: the name of the specified Matrix. This is a Matrix class.  PreVals.CopyTranspose(a)  The values in Matrix "a" are copied and transposed into the Matrix "PreVals".  
CopyInvert(Matrix) Implemented in Build138. 
Makes a copy of the supplied Matrix and then calls Invert() so that original supplied Matrix is left unchanged.  Bit  Matrix: the name of the specified Matrix. This is a Matrix class.  InvertOK = CIv1.Invert(Iv1) 
CopySolve(Matrix, Array) Implemented in Build138.25617. 
Makes a copy of the supplied Matrix and then calls Solve(Array) so that original supplied Matrix is left unchanged.  Bit  Matrix: the name of the specified Matrix. This is a Matrix class. Array: the name of the specified RHS, which is overwritten. This is an Array class. 
SolveOK = M.CopySolve(A, X) 
Watch
New Build 138 Syntax (for Build138.24698 or later) : The matrix Watch function has been greatly improved in Build138.24698.
 Syntax is now simplified to "Watch MMM", where MMM is the name of the Matrix.
 If the "@" symbol is included (eg "Watch [email protected]"), then the matrix elements will be read only fields in the access window.
 The values for the matrix are shown after the project has started solving.
 The values are shown in a grid view on the M_{x} tab pages. (Improved from the old single list view).
 The maximum size for the grid view is 50 columns x 1000 rows, but all the possible tags always work even if not visible.
 If you have referenced a tag from the matrix (eg in trend), and then reduced the matrix size, it will return NAN (*) or become an invalid tag (depending on when matrix is resized).
Syntax for earlier builds To make the matrix variables visible in the access window the Watch command can be used.
 Individual elements in the matrix can be made visible  e.g. "Watch A[2,1]" or "Watch [email protected][2,1]" for element at row 2 and column 1.
 A range of matrix elements can be made visible  e.g. "Watch A[All,5,2]" shows first 5 rows and 2 columns.
 If the "@" symbol is included, then the matrix elements will be read only fields in the access window.
Matrix with Constant Values
The user may declare a matrix with a set of constant values. This allows the user to set up a table of look up values, without having to read them into the matrix via a CSV file.
The syntax is:
Matrix LookupTable = {{a1,a2,a3,....}, {b1,b2,b3,....}, {c1,c2,c3,....}} where a1, a2, b1, etc are real numbers.
Notes:
 Each group is a row, so {a1,a2,a3,....} is the first row of the Matrix.
 If the number of elements in each row differs, the maximum number is used to set the number of colums in the Matrix. The missing elements are initialised to zero.
 The Matrix is Read Only so data elements cannot be set, the Matrix resized, etc.
Caution
Using a GetAt within a SetAt can sometimes fail.
;For example: a.SetAt(i, j, a.GetAt(i+1, j)) ;This can sometimes fail ;The solution is to use a temporary variable to first retrieve the GetAt value and then call SetAt as follows: Real Tmp Tmp = a.GetAt(i+1, j) a.SetAt(i, j, Tmp)
Solving Systems of Equations
For a single solution of an equation AX = B, where B is an array, use
A.Solve(B)
Both the original matrix and the RHS are overwritten, so the solution is now in the array B. If you don't want to overwrite the original matrix, use CopySolve
M.CopySolve(A, B)
B is again overwritten with the solution; if you don't want this, make a copy first.
For solving repeated sets of equations with the same fixed matrix, calculate the inverse (do this in OnInitialize), then use matrix multiplication. via MultArray or CopyMultArray.
Examples
Example 1  Example 2 

Matrix TestMatrix, TestMatrix1, TestMatrix2, TestMatrix3 Matrix Table1 = { {2, 5, 10}, {1, 3, 6} } Real [email protected], [email protected], [email protected], [email protected], [email protected] Long [email protected], [email protected] Array TestRowValue = {25, 30, 35} Array TestColValue = {5, 10} Array TestRow, TestCol Bit [email protected], [email protected] Sub InitialiseSolution() TestMatrix.Copy(Table1) SumV = TestMatrix.Sum() AverageV = TestMatrix.Avg() MinimumV = TestMatrix.Min() MaximumV = TestMatrix.Max() TestMatrix.Scale(2) TestMatrix.Transpose() RowCount = TestMatrix.GetRowCount() ColCount = TestMatrix.GetColCount() TestMatrix1.SetSize(2,3) TestMatrix2.Copy(Table1) TestMatrix3.SetSize(2,3) TestMatrix2.GetRow(0, TestRow) TestMatrix2.GetCol(0, TestCol) TestMatrix1.SetRow(1, TestRowValue) TestMatrix1.SetCol(0, TestColValue) TestMatrix3.Add(TestMatrix2) TestMatrix3.Sub(TestMatrix2) TestMatrix3.Mult(TestMatrix2) TestMatrix3.Div(TestMatrix2) OK = TestMatrix2.MultMatrix(TestMatrix) OK2 = TestMatrix1.MultArray(TestRowValue) EndSub $ 
Matrix a String ProjectFolder, [email protected] Real d*, [email protected] Long [email protected], [email protected], i Bit SaveNow*, [email protected], CopyToClipboard* Sub InitialiseSolution() ProjectFolder = ["PlantModel.System.PrjFolder"] CsvFilename = Concatenate(ProjectFolder, "\test.csv") a.SetSize(5, 3) a.setat(2, 2, 2.2) a.setat(0, 1, 0.1) a.setat(4, 1, 4.1) d = 2^0.5 RowCount = a.GetRowCount() ColCount = a.GetColCount() EndSub a.SetAt(1, 1, d) i = 0 Col1Sum = 0.0 while (i<RowCount) Col1Sum = Col1Sum + a.GetAt(i, 1) i = i + 1 endWhile if (SaveNow) SaveNow = false OK = a.Save(CsvFilename) if (NOT OK) LogError(Concatenate("Matrix data not saved to file ", CsvFilename)) endif endif if (CopyToClipboard) CopyToClipboard = false a.CopyToClipboard() endif $ 