Skip to content

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:

local Matrix = require 'engine/math/matrix'

Reference

Operators

+

+(Matrix a, Matrix b): Matrix

Add two matrices component-wise

-

-(): Matrix

Unary minus

*

*(Matrix a, Matrix b|number): Matrix

Multiply matrix by another matrix or scalar

/

/(Matrix a, Matrix b|number): Matrix

Divide matrix by another matrix or scalar

^

^(Matrix a, number|'T'|'*'): Matrix

Power, transpose ('T') or complex conjugate ('*')

==

==(Matrix a, Matrix b): boolean

Check equality between matrices

new4x4

static new4x4(data)

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

static new3x3(data)

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

new(rows, columns, data)

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 table
  • columns (number|string): Number of columns, or "I" for identity
  • data (number|table): Fill value (number) or table of values

Returns

  • Matrix: matrix

add

static add(A, B)

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

static sub(A, B)

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

static mul(A, B)

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

static div(A, B)

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 singular
  • number?: of m2 if inversion fails

mulnum

static mulnum(A, num)

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

static divnum(A, num)

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

mulVec3(vec)

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

mulVec4(vec)

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

static pow(m1, num)

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 singular
  • integer?: of the matrix when inversion fails

det

static det(A)

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

static dogauss(mtx)

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 success
  • integer?: of the matrix on failure

invert

static invert(M)

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 singular
  • integer?: of the matrix when singular

sqrt

static sqrt(m1, iters)

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

static root(m1, root, iters)

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 root
  • number: error

normf

static normf(mtx)

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

static normmax(mtx)

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

static round(mtx, idp)

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

static random(mtx, start, stop, idp)

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

static type(mtx)

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

static copy(m1)

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

static transpose(A)

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

static subm(m1, i1, j1, i2, j2)

Extract a submatrix from a matrix.

Extracts rows from i1 to i2 and columns from j1 to j2.

Parameters

  • m1 (Matrix): source matrix
  • i1 (number): starting row index
  • j1 (number): starting column index
  • i2 (number): ending row index
  • j2 (number): ending column index

Returns

  • Matrix: extracted submatrix

concath

static concath(m1, m2)

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 matrix
  • m2 (Matrix): right matrix

Returns

  • Matrix: matrix

concatv

static concatv(m1, m2)

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 matrix
  • m2 (Matrix): bottom matrix

Returns

  • Matrix: matrix

rotl

static rotl(m1)

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

static rotr(m1)

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

static tostring(mtx, formatstr)

Convert a matrix to a string representation.

Returns a human-readable string representation of the matrix.

Parameters

  • mtx (Matrix): matrix to convert
  • formatstr (string?): optional format string for numbers (e.g., "%.2f")

Returns

  • string: representation of the matrix

print

static print()

Print a matrix to the console.

Prints a human-readable string representation of the matrix to stdout.

latex

static latex(mtx, align)

Generate a LaTeX representation of a matrix.

Returns a LaTeX string that can be used in mathematical documents.

Parameters

  • mtx (Matrix): matrix to convert
  • align (string?): alignment option: "c" (center), "l" (left), "r" (right)

Returns

  • string: representation of the matrix

rows

static rows(mtx)

Get the number of rows in a matrix.

Parameters

  • mtx (Matrix): matrix

Returns

  • number: of rows

columns

static columns(mtx)

Get the number of columns in a matrix.

Parameters

  • mtx (Matrix): matrix

Returns

  • number: of columns

size

static size(mtx)

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 rows
  • number: of columns
  • number?: depth (only for tensors)

getelement

static getelement(mtx, i, j)

Get an element from a matrix.

Returns the element at row i, column j.

Parameters

  • mtx (Matrix): matrix
  • i (number): row index
  • j (number): column index

Returns

  • any: element at (i, j), or nil if out of bounds

setelement

static setelement(mtx, i, j, value)

Set an element in a matrix.

Sets the value at row i, column j.

Parameters

  • mtx (Matrix): matrix (modified in-place)
  • i (number): row index
  • j (number): column index
  • value (any): value to set

Returns

  • number: on success, nil on failure

ipairs

static ipairs(mtx)

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

static scalar(m1, m2)

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

static cross(m1, m2)

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

static len(m1)

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

static replace(m1, func)

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 transform
  • func (function): function to apply to each element: func(element, ...) -> newvalue

Returns

  • Matrix: matrix with transformed elements

elementstostrings

static elementstostrings(mtx)

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

static solve(m1)

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