Matrix
The Matrix class provides comprehensive matrix operations implemented with Lua tables, supporting arithmetic functions, determinant calculation, inversion, and solving systems of linear equations using Gauss-Jordan elimination. It handles various matrix types including complex and symbolic matrices, allowing for versatile applications from simple to advanced mathematical computations. Typical use cases include matrix addition, multiplication, transposition, and manipulation in scientific computing, engineering, and data analysis tasks within Lua environments.
Usage
To use this class, add the following require at the top of your script:
Reference
Operators
+
Add two matrices component-wise
-
Unary minus
*
Multiply matrix by another matrix or scalar
/
Divide matrix by another matrix or scalar
^
Power, transpose ('T') or complex conjugate ('*')
==
Check equality between matrices
new4x4
Create a new 4×4 matrix.
If no data is provided, this returns the 4×4 identity matrix \(I\). If an array of numbers is provided, it fills the matrix row by row.
Parameters
data(table): optional array of 16 numbers to fill the matrix
Returns
Matrix: 4×4 matrix
new3x3
Create a new 3×3 matrix.
If no data is provided, this returns the 3×3 identity matrix \(I\). If an array of numbers is provided, it fills the matrix row by row.
Parameters
data(table): optional array of 9 numbers to fill the matrix
Returns
Matrix: 3×3 matrix
new
Create a new matrix
Usage patterns:
- Matrix:new(rows, columns, data) Create a matrix of size rows × columns. If data is a number, all values are initialized with that number. If data is a table, values are filled row by row.
- Matrix:new(rows, "I") Create an identity matrix of size rows × rows.
- Matrix:new(table) If table is a 2D array (table of tables), wrap it as a Matrix. If table is a simple array {x, y, z}, create a 3×1 vector matrix.
Parameters
rows(number|table): Number of rows or an initializer tablecolumns(number|string): Number of columns, or "I" for identitydata(number|table): Fill value (number) or table of values
Returns
Matrix: matrix
add
note: real and complex matrices may be added, subtracted, etc. real and symbolic matrices may also be added, subtracted, etc. but one should avoid using symbolic matrices with complex ones since it is not clear which metatable then is used Add two matrices element-wise.
The result is defined as \(C = A + B\) with \(c_{ij} = a_{ij} + b_{ij}\). Matrix \(B\) may be of bigger size than matrix \(A\).
Parameters
A(Matrix): first matrix \(A\)B(Matrix): second matrix \(B\)
Returns
Matrix: of addition \(A + B\)
sub
Subtract two matrices element-wise.
The result is defined as \(C = A - B\) with \(c_{ij} = a_{ij} - b_{ij}\). Matrix \(B\) may be of bigger size than matrix \(A\).
Parameters
A(Matrix): first matrix \(A\)B(Matrix): second matrix \(B\)
Returns
Matrix: of subtraction \(A - B\)
mul
Multiply two matrices.
The number of columns of matrix \(A\) must equal the number of rows of matrix \(B\): The result is defined as \(C = A \cdot B\) with \(c_{ij} = \sum_k a_{ik} b_{kj}\).
Parameters
A(Matrix): first matrix \(A\)B(Matrix): second matrix \(B\)
Returns
Matrix: of multiplication \(A \cdot B\)
div
Divide two matrices.
Division is defined as multiplication with the inverse of the second matrix: \(A / B = A \cdot B^{-1}\). The number of columns of matrix \(A\) must equal the number of rows of matrix \(B\): The matrix \(B\) must be square and non-singular, to be invertible. On failure, returns \(B\) and the rank of \(B\).
Parameters
A(Matrix): numerator matrix \(A\)B(Matrix): denominator matrix \(B\)
Returns
Matrix|nil: of division \(A \cdot B^{-1}\), or nil if singularnumber?: of m2 if inversion fails
mulnum
Multiply a matrix with a scalar.
The scalar may be a real number or a complex number. Strings are first attempted to be parsed as complex numbers; if that fails, they are treated as symbols. The result is defined as \(C = \alpha \cdot A\) with \(c_{ij} = \alpha \, a_{ij}\).
Parameters
A(Matrix): matrix \(A\)num(number|string): scalar multiplier \(\alpha\)
Returns
Matrix: of scalar multiplication \(\alpha \cdot A\)
divnum
Divide a matrix by a scalar.
The scalar may be a real number or a complex number. Strings are first attempted to be parsed as complex numbers; if that fails, they are treated as symbols. The result is defined as \(C = A / \alpha\) with \(c_{ij} = a_{ij} / \alpha\).
Parameters
A(Matrix): matrix \(A\)num(number|string): scalar divisor \(\alpha\)
Returns
Matrix: of division \(A / \alpha\)
mulVec3
Multiply a 3×3 matrix with a Vector3.
The result is a Vector3 \(v' = A \cdot v\).
Parameters
vec(Vector3): vector \(v\)
Returns
Vector3: of multiplication
mulVec4
Multiply a 4×4 matrix with a Vector4.
The result is a Vector4 \(v' = A \cdot v\).
Parameters
vec(Vector4): vector \(v\)
Returns
Vector4: of multiplication
pow
Raise a matrix to an integer power.
The matrix must be square. If the exponent is negative, the matrix is inverted first. If inversion fails, returns nil and the rank of the matrix.
Parameters
m1(Matrix): matrix to raise \(M\)num(number): integer exponent \(n\)
Returns
Matrix|nil: of \(M^n\), or nil if singularinteger?: of the matrix when inversion fails
det
Calculate the determinant :math:`det(A)` of a square matrix :math:`A`.
The matrix must be square \(n \times n\). Works for symbolic matrices up to 3×3, and numeric matrices of any size. The determinant is a scalar value that represents the scaling factor of the linear transformation defined by the matrix. Geometrically, it represents the area (for 2×2) or volume (for 3×3) spanned by the columns of the matrix.
Parameters
A(Matrix): square matrix \(A\)
Returns
number: \(\det(A)\)
dogauss
Perform Gauss-Jordan elimination on a matrix.
This function modifies the matrix in-place to convert it to reduced row echelon form. Uses partial pivoting for numerical stability.
Parameters
mtx(Matrix): matrix to transform (modified in-place)
Returns
boolean: on successinteger?: of the matrix on failure
invert
Compute the inverse of a matrix.
The inverse \(M^{-1}\) of a matrix \(M\) is defined such that \(M \cdot M^{-1} = I\), where \(I\) is the identity matrix. The matrix \(M\) must be square and non-singular.
On success: returns the inverted matrix. On failure: returns nil and the rank of the matrix.
Parameters
M(Matrix): Matrix to invert
Returns
Matrix|nil: matrix or nil if singularinteger?: of the matrix when singular
sqrt
Calculate the square root of a matrix using the Denman-Beavers iteration. Calculate the square root of a matrix using the Denman-Beavers iteration.
The matrix must be square and invertible. Uses the iteration: \(Y_{k+1} = \frac{1}{2}(Y_k + Z_k^{-1})\), \(Z_{k+1} = \frac{1}{2}(Z_k + Y_k^{-1})\)
Parameters
m1(Matrix): square matrix \(M\)iters(number?): maximum number of iterations (default: auto until convergence)
Returns
Matrix: root \(M^{1/2}\)Matrix: square root \(M^{-1/2}\)number: error between \((M^{1/2})^2\) and \(M\)
root
Calculate the nth root of a matrix.
The matrix must be square and invertible. Uses iterative computation.
Parameters
m1(Matrix): square matrix \(M\)root(number): the root degree \(n\)iters(number?): maximum number of iterations
Returns
Matrix: root \(M^{1/n}\)Matrix: nth rootnumber: error
normf
Calculate the Frobenius norm of a matrix.
The Frobenius norm is defined as \(\|A\|_F = \sqrt{\sum_{i,j} |a_{ij}|^2}\). Works for numeric, complex, and symbolic matrices.
Parameters
mtx(Matrix): matrix \(A\)
Returns
number: Frobenius norm \(\|A\|_F\)
normmax
Calculate the max (infinity) norm of a matrix.
The max norm is defined as \(\|A\|_\infty = \max_i \sum_j |a_{ij}|\). Does not work with symbolic matrices.
Parameters
mtx(Matrix): matrix \(A\)
Returns
number: max norm \(\|A\|_\infty\)
round
Round all elements of a matrix.
Rounds each element to the specified number of decimal places. Modifies the matrix in-place and returns it.
Parameters
mtx(Matrix): matrix to round (modified in-place)idp(number?): number of decimal places (default: 0)
Returns
Matrix: modified matrix
random
Fill a matrix with random values.
Modifies the matrix in-place with random values in the specified range.
Parameters
mtx(Matrix): matrix to fill with random values (modified in-place)start(number?): minimum value (default: -10)stop(number?): maximum value (default: 10)idp(number?): decimal precision divisor (default: 1)
Returns
Matrix: modified matrix
type
Get the type of a matrix.
Returns the element type of the matrix: "number" for numeric matrices, "complex" for complex matrices, "symbol" for symbolic matrices, or "tensor" for tensor matrices.
Parameters
mtx(Matrix): matrix to check
Returns
string: matrix type: "number", "complex", "symbol", or "tensor"
copy
Create a deep copy of a matrix.
Creates a new matrix with the same values as the original. Works for numeric, complex, and symbolic matrices.
Parameters
m1(Matrix): matrix to copy
Returns
Matrix: new matrix that is a copy of the original
transpose
Transpose a matrix.
The transpose of a matrix \(A\) is a new matrix \(A^T\) obtained by flipping rows and columns, so that the element at row \(i\), column \(j\) in \(A\) becomes the element at row \(j\), column \(i\) in \(A^T\).
Parameters
A(Matrix): matrix to transpose \(A\)
Returns
Matrix: matrix \(A^T\)
subm
Extract a submatrix from a matrix.
Extracts rows from i1 to i2 and columns from j1 to j2.
Parameters
m1(Matrix): source matrixi1(number): starting row indexj1(number): starting column indexi2(number): ending row indexj2(number): ending column index
Returns
Matrix: extracted submatrix
concath
Concatenate two matrices horizontally.
Both matrices must have the same number of rows. Returns a new matrix with m1 on the left and m2 on the right.
Parameters
m1(Matrix): left matrixm2(Matrix): right matrix
Returns
Matrix: matrix
concatv
Concatenate two matrices vertically.
Both matrices must have the same number of columns. Returns a new matrix with m1 on top and m2 on bottom.
Parameters
m1(Matrix): top matrixm2(Matrix): bottom matrix
Returns
Matrix: matrix
rotl
Rotate a matrix 90 degrees to the left.
Returns a new matrix that is rotated 90 degrees counterclockwise.
Parameters
m1(Matrix): matrix to rotate
Returns
Matrix: matrix
rotr
Rotate a matrix 90 degrees to the right.
Returns a new matrix that is rotated 90 degrees clockwise.
Parameters
m1(Matrix): matrix to rotate
Returns
Matrix: matrix
tostring
Convert a matrix to a string representation.
Returns a human-readable string representation of the matrix.
Parameters
mtx(Matrix): matrix to convertformatstr(string?): optional format string for numbers (e.g., "%.2f")
Returns
string: representation of the matrix
Print a matrix to the console.
Prints a human-readable string representation of the matrix to stdout.
latex
Generate a LaTeX representation of a matrix.
Returns a LaTeX string that can be used in mathematical documents.
Parameters
mtx(Matrix): matrix to convertalign(string?): alignment option: "c" (center), "l" (left), "r" (right)
Returns
string: representation of the matrix
rows
Get the number of rows in a matrix.
Parameters
mtx(Matrix): matrix
Returns
number: of rows
columns
Get the number of columns in a matrix.
Parameters
mtx(Matrix): matrix
Returns
number: of columns
size
Get the size of a matrix.
Returns the number of rows and columns. For tensors, also returns the depth.
Parameters
mtx(Matrix): matrix
Returns
number: of rowsnumber: of columnsnumber?: depth (only for tensors)
getelement
Get an element from a matrix.
Returns the element at row i, column j.
Parameters
mtx(Matrix): matrixi(number): row indexj(number): column index
Returns
any: element at (i, j), or nil if out of bounds
setelement
Set an element in a matrix.
Sets the value at row i, column j.
Parameters
mtx(Matrix): matrix (modified in-place)i(number): row indexj(number): column indexvalue(any): value to set
Returns
number: on success, nil on failure
ipairs
Iterate over matrix elements.
Returns an iterator function for use in for loops. Iterates through all elements row by row.
Parameters
mtx(Matrix): matrix to iterate
Returns
function: function
scalar
Calculate the scalar (dot) product of two vectors.
Both arguments must be 3x1 matrices (column vectors). The result is \(a \cdot b = a_x b_x + a_y b_y + a_z b_z\).
Parameters
m1(Matrix): first vector (3x1)m2(Matrix): second vector (3x1)
Returns
number: scalar product
cross
Calculate the cross product of two vectors.
Both arguments must be 3x1 matrices (column vectors). Returns a new vector perpendicular to both input vectors.
Parameters
m1(Matrix): first vector (3x1)m2(Matrix): second vector (3x1)
Returns
Matrix: product vector (3x1)
len
Calculate the length (magnitude) of a vector.
The argument must be a 3x1 matrix (column vector). Returns \(\sqrt{x^2 + y^2 + z^2}\).
Parameters
m1(Matrix): vector (3x1)
Returns
number: vector length
replace
Replace each element of a matrix using a function.
Applies a function to each element, returning a new matrix with the results.
Parameters
m1(Matrix): matrix to transformfunc(function): function to apply to each element: func(element, ...) -> newvalue
Returns
Matrix: matrix with transformed elements
elementstostrings
Convert all matrix elements to strings.
Returns a new matrix with all elements converted to string representation.
Parameters
mtx(Matrix): matrix to convert
Returns
Matrix: matrix with string elements
solve
Solve a symbolic matrix to numeric values.
Converts a symbolic matrix to a numeric matrix by evaluating the symbolic expressions. Only works with matrices of type "symbol".
Parameters
m1(Matrix): symbolic matrix
Returns
Matrix: matrix