///|
/// Indexing interface that provides mutable access to elements along a matrix
/// row.
///
/// Fields:
///
/// Since this struct is not marked with any visibility modifier, it is abstract
/// and users cannot directly access its fields. The struct can only be used
/// through its associated methods.
///
/// ### Performance Best Practices:
///
/// 1. **Use Direct Access (Recommended)**: While `m[i][j]` is convenient, `Matrix::get(row, col)`
/// and `Matrix::set(row, col, value)` are significantly faster as they avoid creating temporary
/// Lens objects and closures. Prefer these for performance-critical code.
/// 2. **Avoid Repeated Lens Allocation**: If you must use `Lens`, accessing `m[i][j]` in a loop
/// creates a `Lens` object on every call to `m[i]`. Cache the row lens:
/// ```moonbit nocheck
/// let row = m[i] // Allocate once
/// for j in 0.. Int32 {
self.row
}
///|
/// Returns the number of columns in the matrix.
///
/// Parameters:
///
/// * `self` : The matrix to query.
///
/// Returns:
///
/// `Int` - The number of columns in the matrix.
///
/// Example:
///
/// ```moonbit nocheck
/// let m = @mutable.Matrix::from_2d_array([[1, 2, 3], [4, 5, 6]])
/// inspect(m.col(), content="3")
/// ```
///
pub fn[T] Matrix::col(self : Matrix[T]) -> Int32 {
self.col
}
///|
/// Converts a matrix to its string representation in a readable format.
///
/// Parameters:
///
/// * `self` : The matrix to convert to a string.
///
/// Returns a string representation of the matrix where each row is enclosed in
/// vertical bars (`|`), elements are separated by commas and spaces, and rows
/// are separated by newlines.
///
/// Example:
///
/// ```moonbit nocheck
/// let m = Matrix::from_2d_array([[1, 2, 3], [4, 5, 6]])
/// inspect(m, content="|1, 2, 3|\n|4, 5, 6|")
/// ```
///
pub impl[T : Show] Show for Matrix[T] with fn to_string(self) {
let logger = StringBuilder()
self.output(logger)
logger.to_string()
}
///|
/// Implements output functionality for `Matrix[T]` by writing its string
/// representation to a logger.
///
/// Parameters:
///
/// * `self` : The matrix to be output.
/// * `logger` : The logger to write the matrix representation to.
///
pub impl[T : Show] Show for Matrix[T] with fn output(self, logger) {
for i in 0.. {
logger.write_object(x)
if c < self.col - 1 {
logger.write_string(", ")
}
})
logger.write_char('|')
if i < self.row - 1 {
logger.write_char('\n')
}
}
}
///|
/// Applies a function to every element of the matrix, creating a new matrix
/// with the transformed elements.
///
/// Parameters:
///
/// * `self` : The input matrix to transform.
/// * `f` : The function to apply to each element, taking a value of type `T`
/// and returning a value of type `U`.
///
/// Returns a new matrix with the same dimensions as the input matrix, where
/// each element is the result of applying the function `f` to the corresponding
/// element in the input matrix.
///
/// Example:
///
/// ```moonbit nocheck
/// let m = @mutable.Matrix::from_2d_array([[1, 2], [3, 4]])
/// let doubled = m.map(fn(x) { x * 2 })
/// inspect(doubled, content="|2, 4|\n|6, 8|")
/// ```
///
pub fn[T, U] Matrix::map(self : Matrix[T], f : (T) -> U) -> Matrix[U] {
{ row: self.row, col: self.col, data: self.data.map(f), }
}
///|
/// Applies a function to every element of the matrix with its index, creating a
/// new matrix with the transformed elements.
///
/// Parameters:
///
/// * `self` : The input matrix to transform.
/// * `f` : The function to apply to each element, taking the row index, column
/// index, and value of type `T`, and returning a value of type `U`.
///
/// Returns a new matrix with the same dimensions as the input matrix.
///
/// Example:
///
/// ```moonbit nocheck
/// let m = @mutable.Matrix::from_2d_array([[1, 2], [3, 4]])
/// let m2 = m.mapi(fn(i, j, x) { x + i + j })
/// inspect(m2, content="|1, 3|\n|4, 6|")
/// ```
///
pub fn[T, U] Matrix::mapi(
self : Matrix[T],
f : (Int32, Int32, T) -> U,
) -> Matrix[U] {
let row = self.row
let col = self.col
if row == 0 || col == 0 {
return { row, col, data: [], }
}
// Avoid division and modulo in the loop by using nested loops.
// This is significantly faster for large matrices.
let data = Array::make(row * col, f(0, 0, self.data[0]))
let mut idx = 0
for i in 0.. T) -> Unit {
self.data.map_in_place(f)
}
///|
/// Converts a matrix to its transpose representation without copying the
/// underlying data.
///
/// Parameters:
///
/// * `self` : The matrix to convert to transpose form.
///
/// Returns a `Transpose[T]` that represents the transposed view of the original
/// matrix, where rows and columns are swapped but the underlying data array
/// remains shared.
///
/// Example:
///
/// ```moonbit nocheck
/// let m = @mutable.Matrix::from_2d_array([[1, 2, 3], [4, 5, 6]])
/// inspect(m.to_transpose(), content="|1, 4|\n|2, 5|\n|3, 6|")
/// // The transpose has 3 rows and 2 columns (original was 2x3)
/// ```
///
pub fn[T] Matrix::to_transpose(self : Matrix[T]) -> Transpose[T] {
self
}
///|
/// Applies a transformation function to all elements in a specific row of the
/// matrix in-place.
///
/// Parameters:
///
/// * `self` : The matrix to modify.
/// * `row` : The zero-based index of the row to transform.
/// * `f` : The transformation function to apply to each element in the row.
///
/// Example:
///
/// ```moonbit nocheck
/// let m = @mutable.Matrix::from_2d_array([[1, 2, 3], [4, 5, 6]])
/// m.map_row_inplace(0, fn(x) { x * 2 })
/// // The first row becomes [2, 4, 6], second row remains [4, 5, 6]
/// ```
///
#alias(map_row_in_place, deprecated)
pub fn[T] Matrix::map_row_inplace(
self : Matrix[T],
row : Int32,
f : (T) -> T,
) -> Unit {
let offset = self.matrix_row_offset(row)
let data = self.data
for i in 0.. T,
) -> Unit {
let checked_col = self.matrix_checked_col(col)
let rows = self.row
let cols = self.col
let data = self.data
let mut idx = checked_col
for _ in 0.. Unit) -> Unit {
self.data.each(f)
}
///|
/// Iterates over each element of the matrix with its index, calling the
/// provided function for each element.
///
/// Parameters:
///
/// * `self` : The matrix to iterate over.
/// * `f` : A function that takes an index and an element value. The index
/// represents the linear position in the underlying array (calculated as `row
/// * col_count + col`).
pub fn[T] Matrix::eachi(self : Matrix[T], f : (Int32, T) -> Unit) -> Unit {
self.data.eachi(f)
}
///|
/// Iterates through all elements of the matrix, calling the provided function
/// with the row index, column index, and value for each element.
///
/// Parameters:
///
/// * `self` : The matrix to iterate through.
/// * `f` : A function that takes three parameters: the row index (Int), the
/// column index (Int), and the element value (T). This function is called for
/// each element in the matrix.
pub fn[T] Matrix::each_row_col(
self : Matrix[T],
f : (Int32, Int32, T) -> Unit,
) -> Unit {
let rows = self.row
let cols = self.col
let data = self.data
for i in 0.. Unit,
) -> Unit {
let offset = self.matrix_row_offset(row)
let data = self.data
for i in 0.. Unit,
) -> Unit {
let offset = self.matrix_row_offset(row)
let data = self.data
for i in 0.. Unit,
) -> Unit {
let checked_col = self.matrix_checked_col(col)
let rows = self.row
let cols = self.col
let data = self.data
for i in 0.. Unit,
) -> Unit {
let mut idx = self.matrix_checked_col(col)
let cols = self.col
for i = 0; i < self.row; i = i + 1 {
f(i, self.data[idx])
idx += cols
}
}
///|
/// Creates a deep copy of the matrix with the same dimensions and element
/// values.
///
/// Parameters:
///
/// * `self` : The matrix to be copied.
///
/// Returns a new matrix that is an independent copy of the original matrix.
///
/// Example:
///
/// ```moonbit nocheck
/// let original = @mutable.Matrix::from_2d_array([[1, 2], [3, 4]])
/// let copy = original.copy()
/// copy[0][0] = 99
/// inspect(original[0][0], content="1") // Original remains unchanged
/// inspect(copy[0][0], content="99") // Copy is modified
/// ```
///
pub fn[T] Matrix::copy(self : Matrix[T]) -> Matrix[T] {
{ row: self.row, col: self.col, data: self.data.copy(), }
}
///|
/// Creates a new matrix with specified dimensions using a generator function.
///
/// Parameters:
///
/// * `row` : The number of rows in the matrix.
/// * `col` : The number of columns in the matrix.
/// * `f` : A function that takes row and column indices and returns the element
/// at that position.
///
/// Returns a new `Matrix[A]` with the specified dimensions where each element
/// is generated by calling the function with its row and column indices.
///
/// Example:
///
/// ```moonbit nocheck
/// // Create a 3x3 identity matrix
/// let identity = Matrix::make(3, 3, fn(i, j) { if i == j { 1 } else { 0 } })
/// inspect(identity, content="|1, 0, 0|\n|0, 1, 0|\n|0, 0, 1|")
/// // Create a matrix where each element equals its row index plus column index
/// let sum_matrix = Matrix::make(2, 3, fn(i, j) { i + j })
/// inspect(sum_matrix, content="|0, 1, 2|\n|1, 2, 3|")
/// ```
///
pub fn[A] Matrix::make(
row : Int32,
col : Int32,
f : (Int32, Int32) -> A,
) -> Matrix[A] {
guard row >= 0 && col >= 0 else {
abort("Matrix dimensions must be non-negative")
}
if row == 0 || col == 0 {
return { row, col, data: [], }
}
let init = f(0, 0)
let data = Array::make(row * col, init)
for i = 0; i < row; i = i + 1 {
let r_off = i * col
for j = 0; j < col; j = j + 1 {
data[r_off + j] = f(i, j)
}
}
{ row, col, data, }
}
///|
/// Creates a new matrix with the specified dimensions where all elements are
/// initialized to the same value.
///
/// Parameters:
///
/// * `row` : The number of rows in the matrix.
/// * `col` : The number of columns in the matrix.
/// * `elem` : The value to initialize all elements in the matrix.
///
/// Returns a new `Matrix[T]` with all elements set to `elem`.
///
/// Example:
///
/// ```moonbit nocheck
/// let m = Matrix::new(2, 3, 42)
/// inspect(m, content="|42, 42, 42|\n|42, 42, 42|")
/// ```
///
pub fn[T] Matrix::new(row : Int32, col : Int32, elem : T) -> Matrix[T] {
guard row >= 0 && col >= 0 else {
abort("Matrix dimensions must be non-negative")
}
if row == 0 || col == 0 {
return { row, col, data: [], }
}
{ row, col, data: Array::make(row * col, elem), }
}
///|
/// Creates a matrix from a 2D array.
///
/// Parameters:
///
/// * `arr` : A 2D array where each sub-array represents a row of the matrix.
///
/// Returns a new `Matrix[T]` with the same dimensions and elements as the input
/// 2D array.
///
/// Panics if the input array is empty or if any sub-array is empty.
///
/// Example:
///
/// ```moonbit nocheck
/// let data = [[1, 2, 3], [4, 5, 6]]
/// let matrix = Matrix::from_2d_array(data)
/// inspect(matrix, content="|1, 2, 3|\n|4, 5, 6|")
/// ```
///
pub fn[T] Matrix::from_2d_array(arr : Array[Array[T]]) -> Matrix[T] {
let row = arr.length()
if row == 0 {
return { row: 0, col: 0, data: [], }
}
let col = arr[0].length()
for row_arr in arr {
guard row_arr.length() == col else {
abort("Matrix::from_2d_array: rows must have equal length")
}
}
if col == 0 {
return { row, col, data: [], }
}
let data = Array::make(row * col, arr[0][0])
for i in 0.. T {
self.data[self.matrix_index_offset(row, col)]
}
///|
pub fn[T] Matrix::set(
self : Matrix[T],
row : Int32,
col : Int32,
elem : T,
) -> Unit {
self.data[self.matrix_index_offset(row, col)] = elem
}
///|
/// Creates a matrix from a flat array with specified dimensions.
///
/// Parameters:
///
/// * `row` : The number of rows in the matrix.
/// * `col` : The number of columns in the matrix.
/// * `data` : A flat array containing the matrix elements in row-major order.
///
/// Returns a new matrix with the specified dimensions.
///
/// Panics if the product of `row` and `col` does not equal the length of
/// `data`.
///
/// Example:
///
/// ```moonbit nocheck
/// let data = [1, 2, 3, 4, 5, 6]
/// let matrix = @mutable.Matrix::from_array(2, 3, data)
/// inspect(matrix, content="|1, 2, 3|\n|4, 5, 6|")
/// ```
///
pub fn[T] Matrix::from_array(
row : Int32,
col : Int32,
data : Array[T],
) -> Matrix[T] {
guard row >= 0 && col >= 0 else {
abort("Matrix dimensions must be non-negative")
}
guard row * col == data.length() else {
abort("Matrix::from_array: data length does not match dimensions")
}
{ row, col, data, }
}
///|
/// Returns a lens that provides indexed access to a specific row of the matrix.
///
/// **Performance Note**: Calling `m[row]` allocates a new `Lens` object and two closures.
/// For performance-critical bulk operations on a row, it is highly recommended to:
/// 1. **Cache the lens**: Store the result of `m[row]` in a variable before the loop.
/// 2. **Use built-in tools**: For common operations, use `each_row`, `map_row_inplace`,
/// or `iter_row` which avoid Lens overhead entirely.
///
/// Parameters:
///
/// * `self` : The matrix to access.
/// * `row` : The zero-based index of the row to access.
///
/// Returns a `Lens[T]` object that allows getting and setting elements in the
/// specified row by column index.
///
/// Example:
///
/// ```moonbit nocheck
/// let m = @mutable.Matrix::from_2d_array([[1, 2, 3], [4, 5, 6]])
/// let row_lens = m[1] // Caching the lens for row 1
/// inspect(row_lens[0], content="4") // Access element at column 0
/// row_lens[2] = 10 // Set element at column 2
/// inspect(m[1][2], content="10")
/// ```
///
#alias("_[_]")
pub fn[T] Matrix::at(self : Matrix[T], row : Int32) -> Lens[T] {
ignore(self.matrix_row_offset(row))
{ data: self, fst: row, is_transpose: false, }
}
///|
/// Retrieves the value at the specified column index from the lens.
///
/// Parameters:
///
/// * `self` : The lens to access.
/// * `col` : The column index to retrieve the value from.
///
/// Returns the value at the specified column index.
///
#alias("_[_]")
pub fn[T] Lens::at(self : Lens[T], snd : Int32) -> T {
if self.is_transpose {
self.data.get(snd, self.fst)
} else {
self.data.get(self.fst, snd)
}
}
///|
/// Sets the value at the specified column index in the lens.
///
/// Parameters:
///
/// * `self` : The lens object to modify.
/// * `col` : The column index where the value should be set.
/// * `elem` : The value to set at the specified column index.
///
/// Example:
///
/// ```moonbit
/// let m = Matrix::from_2d_array([[1, 2, 3], [4, 5, 6]])
///
#alias("_[_]=_")
pub fn[T] Lens::set(self : Lens[T], snd : Int32, elem : T) -> Unit {
if self.is_transpose {
self.data.set(snd, self.fst, elem)
} else {
self.data.set(self.fst, snd, elem)
}
}
///|
/// Multiplies two matrices using standard matrix multiplication.
///
/// Parameters:
///
/// * `self` : The left matrix operand.
/// * `other` : The right matrix operand.
///
/// Returns a new matrix that is the product of `self` and `other`.
///
/// Panics if the number of columns in `self` does not equal the number of rows
/// in `other`.
///
/// Example:
///
/// ```moonbit nocheck
/// let a = @mutable.Matrix::from_2d_array([[1, 2], [3, 4]])
/// let b = @mutable.Matrix::from_2d_array([[5, 6], [7, 8]])
/// let result = a * b
/// inspect(result, content="|19, 22|\n|43, 50|")
/// ```
///
pub impl[T : AddMonoid + Mul] Mul for Matrix[T] with fn mul(
self : Matrix[T],
other : Matrix[T],
) -> Matrix[T] {
guard self.col == other.row else { abort("Matrix::mul: dimension mismatch") }
self.unchecked_matmul(other)
}
///|
/// Multiplies two matrices without checking shape compatibility.
///
/// Callers must ensure `self.col() == other.row()` before calling this method.
pub fn[T : AddMonoid + Mul] Matrix::unchecked_matmul(
self : Matrix[T],
other : Matrix[T],
) -> Matrix[T] {
let row = self.row
let col = other.col
let inner = self.col
let data = Array::make(row * col, Zero::zero())
let self_data = self.data
let other_data = other.data
if should_use_packed_rhs_matmul(row, col, inner) {
let packed_rhs = pack_rhs_columns(inner, col, other_data)
matmul_packed_rhs_into(row, col, inner, self_data, packed_rhs, data)
} else {
matmul_unrolled_into(row, col, inner, self_data, other_data, data)
}
{ row, col, data, }
}
///|
fn should_use_packed_rhs_matmul(
row : Int32,
col : Int32,
inner : Int32,
) -> Bool {
row >= 4 && col >= 16 && inner >= 16 && row * col * inner >= 4096
}
///|
fn[T] pack_rhs_columns(
inner : Int32,
col : Int32,
other_data : Array[T],
) -> Array[T] {
let packed = Array::make(inner * col, other_data[0])
for k = 0; k < inner; k = k + 1 {
let src_row_offset = k * col
for j = 0; j < col; j = j + 1 {
packed[j * inner + k] = other_data[src_row_offset + j]
}
}
packed
}
///|
fn[T : AddMonoid + Mul] matmul_packed_rhs_into(
row : Int32,
col : Int32,
inner : Int32,
self_data : Array[T],
packed_rhs : Array[T],
data : Array[T],
) -> Unit {
let mut result_row_offset = 0
for i = 0; i < row; i = i + 1 {
let self_row_offset = i * inner
let mut j = 0
while j + 3 < col {
let rhs0 = j * inner
let rhs1 = rhs0 + inner
let rhs2 = rhs1 + inner
let rhs3 = rhs2 + inner
let mut sum0 = Zero::zero()
let mut sum1 = Zero::zero()
let mut sum2 = Zero::zero()
let mut sum3 = Zero::zero()
let mut k = 0
while k + 3 < inner {
let a0 = self_data[self_row_offset + k]
let a1 = self_data[self_row_offset + k + 1]
let a2 = self_data[self_row_offset + k + 2]
let a3 = self_data[self_row_offset + k + 3]
sum0 = sum0 +
a0 * packed_rhs[rhs0 + k] +
a1 * packed_rhs[rhs0 + k + 1] +
a2 * packed_rhs[rhs0 + k + 2] +
a3 * packed_rhs[rhs0 + k + 3]
sum1 = sum1 +
a0 * packed_rhs[rhs1 + k] +
a1 * packed_rhs[rhs1 + k + 1] +
a2 * packed_rhs[rhs1 + k + 2] +
a3 * packed_rhs[rhs1 + k + 3]
sum2 = sum2 +
a0 * packed_rhs[rhs2 + k] +
a1 * packed_rhs[rhs2 + k + 1] +
a2 * packed_rhs[rhs2 + k + 2] +
a3 * packed_rhs[rhs2 + k + 3]
sum3 = sum3 +
a0 * packed_rhs[rhs3 + k] +
a1 * packed_rhs[rhs3 + k + 1] +
a2 * packed_rhs[rhs3 + k + 2] +
a3 * packed_rhs[rhs3 + k + 3]
k += 4
}
while k < inner {
let lhs = self_data[self_row_offset + k]
sum0 = sum0 + lhs * packed_rhs[rhs0 + k]
sum1 = sum1 + lhs * packed_rhs[rhs1 + k]
sum2 = sum2 + lhs * packed_rhs[rhs2 + k]
sum3 = sum3 + lhs * packed_rhs[rhs3 + k]
k += 1
}
let out_idx = result_row_offset + j
data[out_idx] = sum0
data[out_idx + 1] = sum1
data[out_idx + 2] = sum2
data[out_idx + 3] = sum3
j += 4
}
while j < col {
let rhs_offset = j * inner
let mut sum = Zero::zero()
for k = 0; k < inner; k = k + 1 {
sum = sum + self_data[self_row_offset + k] * packed_rhs[rhs_offset + k]
}
data[result_row_offset + j] = sum
j += 1
}
result_row_offset += col
}
}
///|
fn[T : AddMonoid + Mul] matmul_unrolled_into(
row : Int32,
col : Int32,
inner : Int32,
self_data : Array[T],
other_data : Array[T],
data : Array[T],
) -> Unit {
let mut result_row_offset = 0
for i = 0; i < row; i = i + 1 {
let self_row_offset = i * inner
for k = 0; k < inner; k = k + 1 {
let lhs = self_data[self_row_offset + k]
let other_row_offset = k * col
let mut j = 0
while j + 3 < col {
let out_idx = result_row_offset + j
data[out_idx] = data[out_idx] + lhs * other_data[other_row_offset + j]
data[out_idx + 1] = data[out_idx + 1] +
lhs * other_data[other_row_offset + j + 1]
data[out_idx + 2] = data[out_idx + 2] +
lhs * other_data[other_row_offset + j + 2]
data[out_idx + 3] = data[out_idx + 3] +
lhs * other_data[other_row_offset + j + 3]
j += 4
}
while j < col {
let out_idx = result_row_offset + j
data[out_idx] = data[out_idx] + lhs * other_data[other_row_offset + j]
j += 1
}
}
result_row_offset += col
}
}
///|
/// Adds two matrices element-wise.
///
/// Parameters:
///
/// * `self` : The first matrix.
/// * `other` : The second matrix to add to the first matrix.
///
/// Returns a new matrix where each element is the sum of the corresponding
/// elements from the input matrices.
///
/// Panics if the matrices have different dimensions (different number of rows
/// or columns).
///
/// Example:
///
/// ```moonbit nocheck
/// let m1 = Matrix::from_2d_array([[1, 2], [3, 4]])
/// let m2 = Matrix::from_2d_array([[5, 6], [7, 8]])
/// let result = m1 + m2
/// inspect(result, content="|6, 8|\n|10, 12|")
/// ```
///
pub impl[T : Add] Add for Matrix[T] with fn add(
self : Matrix[T],
other : Matrix[T],
) -> Matrix[T] {
guard self.col == other.col else { abort("Matrix::add: dimension mismatch") }
guard self.row == other.row else { abort("Matrix::add: dimension mismatch") }
{
data: array_zip_with(self.data, other.data, T::add),
row: self.row,
col: self.col,
}
}
///|
/// Negates all elements in the matrix.
///
/// Parameters:
///
/// * `self` : The matrix to negate.
///
/// Returns a new matrix with all elements negated.
///
/// Example:
///
/// ```moonbit nocheck
/// let m = @mutable.Matrix::from_2d_array([[1, -2], [3, -4]])
/// let negated = -m
/// inspect(negated, content="|-1, 2|\n|-3, 4|")
/// ```
///
pub impl[T : Neg] Neg for Matrix[T] with fn neg(self : Matrix[T]) -> Matrix[T] {
self.map(T::neg)
}
///|
/// Subtracts the second matrix from the first matrix element-wise.
///
/// Parameters:
///
/// * `self` : The matrix from which to subtract (minuend).
/// * `other` : The matrix to subtract (subtrahend).
///
/// Returns a new matrix containing the element-wise difference of the two
/// matrices.
///
/// Example:
///
/// ```moonbit nocheck
/// let m1 =Matrix::from_2d_array([[5, 7], [9, 11]])
/// let m2 =Matrix::from_2d_array([[1, 2], [3, 4]])
/// let result = m1 - m2
/// // result is |4, 5|
/// // |6, 7|
/// inspect(result, content="|4, 5|\n|6, 7|")
/// ```
///
pub impl[T : Add + Neg] Sub for Matrix[T] with fn sub(
self : Matrix[T],
other : Matrix[T],
) -> Matrix[T] {
self + -other
}
///|
/// Multiplies each element of the matrix by a scalar value.
///
/// Parameters:
///
/// * `self` : The matrix to be scaled.
/// * `cst` : The scalar value to multiply each element by.
///
/// Returns a new matrix where each element is the product of the corresponding
/// element in the original matrix and the scalar.
///
/// Example:
///
/// ```moonbit nocheck
/// let m = @mutable.Matrix::from_2d_array([[1, 2], [3, 4]])
/// let scaled = m.scale(2)
/// inspect(scaled, content="|2, 4|\n|6, 8|")
/// ```
///
pub fn[T : Mul] Matrix::scale(self : Matrix[T], cst : T) -> Matrix[T] {
self.map(x => x * cst)
}
///|
/// Adds a constant value to each element of the matrix.
///
/// Parameters:
///
/// * `self` : The matrix to which the constant will be added.
/// * `cst` : The constant value to add to each element.
///
/// Returns a new matrix with the constant added to each element of the original
/// matrix.
///
/// Example:
///
/// ```moonbit nocheck
/// let m = Matrix::from_2d_array([[1, 2], [3, 4]])
/// let result = m.add_constant(5)
/// inspect(result, content="|6, 7|\n|8, 9|")
/// ```
///
pub fn[T : Add] Matrix::add_constant(self : Matrix[T], cst : T) -> Matrix[T] {
self.map(x => x + cst)
}
///|
/// Creates an identity matrix of the specified size.
///
/// Parameters:
///
/// * `size` : The number of rows and columns of the identity matrix.
///
/// Returns a square matrix where diagonal elements are one and all other
/// elements are zero.
///
/// Panics if `size` is negative.
///
/// Example:
///
/// ```moonbit nocheck
/// let id : Matrix[Int] = @mutable.identity(3)
/// inspect(id, content="|1, 0, 0|\n|0, 1, 0|\n|0, 0, 1|")
/// ```
///
pub fn[T : Zero + One] identity(size : Int32) -> Matrix[T] {
Matrix::make(size, size, fn(i, j) {
guard i == j else { Zero::zero() }
One::one()
})
}
///|
/// Checks whether the matrix is a null (zero) matrix by testing if all elements
/// are equal to zero.
///
/// Parameters:
///
/// * `self` : The matrix to check for nullity.
///
/// Returns `true` if all elements in the matrix are zero, `false` otherwise.
///
/// Example:
///
/// ```moonbit nocheck
/// let zero_matrix = @mutable.Matrix::new(2, 2, 0)
/// let non_zero_matrix = @mutable.Matrix::from_2d_array([[1, 0], [0, 1]])
/// inspect(zero_matrix.null(), content="true")
/// inspect(non_zero_matrix.null(), content="false")
/// ```
///
pub fn[T : Compare + Zero] Matrix::null(self : Matrix[T]) -> Bool {
!self.data.iter().any(fn(x) { x != Zero::zero() })
}
///|
/// Computes the adjoint (conjugate transpose) of the matrix.
///
/// Parameters:
///
/// * `self` : The matrix to compute the adjoint of.
///
/// Returns the conjugate transpose of the original matrix.
pub fn[T : Conjugate] Matrix::adjoint(self : Matrix[T]) -> Matrix[T] {
self.transpose().map(T::conjugate)
}
///|
/// Transposes the matrix by swapping rows and columns.
///
/// Parameters:
///
/// * `self` : The matrix to transpose.
///
/// Returns a new matrix that is the transpose of the input matrix, where the
/// element at position (i, j) in the original matrix becomes the element at
/// position (j, i) in the transposed matrix.
///
/// Example:
///
/// ```moonbit nocheck
/// let m = Matrix::from_2d_array([[1, 2, 3], [4, 5, 6]])
/// let transposed = m.transpose()
/// inspect(transposed, content="|1, 4|\n|2, 5|\n|3, 6|")
/// ```
///
pub fn[T] Matrix::transpose(self : Matrix[T]) -> Matrix[T] {
let row = self.row
let col = self.col
if row == 0 || col == 0 {
return { row: col, col: row, data: [], }
}
let init = self.data[0]
let res_data = Array::make(col * row, init)
for i = 0; i < col; i = i + 1 {
let res_row_off = i * row
for j = 0; j < row; j = j + 1 {
res_data[res_row_off + j] = self.data[j * col + i]
}
}
{ row: col, col: row, data: res_data, }
}
///|
/// Swaps the positions of two rows in the matrix.
///
/// Parameters:
///
/// * `self` : The matrix to perform the row swap operation on.
/// * `r1` : The index of the first row to swap.
/// * `r2` : The index of the second row to swap.
///
/// Panics if either `r1` or `r2` is out of bounds (negative or greater than or
/// equal to the number of rows in the matrix).
///
/// Example:
///
/// ```moonbit nocheck
/// let m = @mutable.Matrix::from_2d_array([[1, 2, 3], [4, 5, 6]])
/// m.swap_rows(0, 1)
/// inspect(m, content="|4, 5, 6|\n|1, 2, 3|")
/// ```
///
pub fn[T] Matrix::swap_rows(self : Matrix[T], r1 : Int32, r2 : Int32) -> Unit {
ignore(self.matrix_row_offset(r1))
ignore(self.matrix_row_offset(r2))
let c = self.col
if r1 == r2 {
return
}
let r1_off = r1 * self.col
let r2_off = r2 * self.col
for i = 0; i < c; i = i + 1 {
let tmp = self.data[r1_off + i]
self.data[r1_off + i] = self.data[r2_off + i]
self.data[r2_off + i] = tmp
}
}
///|
/// Swaps two columns in the matrix in-place.
///
/// Parameters:
///
/// * `self` : The matrix whose columns will be swapped.
/// * `c1` : The index of the first column to swap.
/// * `c2` : The index of the second column to swap.
///
/// Panics if either `c1` or `c2` is negative or greater than or equal to the
/// number of columns in the matrix.
///
/// Example:
///
/// ```moonbit nocheck
/// let m = @mutable.Matrix::from_2d_array([[1, 2, 3], [4, 5, 6]])
/// m.swap_cols(0, 2)
/// inspect(m, content="|3, 2, 1|\n|6, 5, 4|")
/// ```
///
pub fn[T] Matrix::swap_cols(self : Matrix[T], c1 : Int32, c2 : Int32) -> Unit {
let checked_c1 = self.matrix_checked_col(c1)
let checked_c2 = self.matrix_checked_col(c2)
let r = self.row
if c1 == c2 {
return
}
let col = self.col
for i = 0; i < r; i = i + 1 {
let row_off = i * col
let idx1 = row_off + checked_c1
let idx2 = row_off + checked_c2
let tmp = self.data[idx1]
self.data[idx1] = self.data[idx2]
self.data[idx2] = tmp
}
}
///|
/// Computes the power of a square matrix using fast exponentiation.
///
/// Parameters:
///
/// * `self` : The square matrix to be raised to a power.
/// * `power` : The non-negative integer exponent.
///
/// Returns the matrix raised to the specified power.
///
/// Example:
///
/// ```moonbit nocheck
/// let m = Matrix::from_2d_array([[1, 2], [3, 4]])
/// let m_squared = m.pow(2).unwrap()
/// // Equivalent to m * m
/// inspect(m_squared, content="|7, 10|\n|15, 22|")
/// ```
///
pub fn[T : Semiring] Matrix::pow(
self : Matrix[T],
power : Int32,
) -> Result[Matrix[T], LinearAlgebraError] {
match ensure_square_checked(self) {
Ok(_) => ()
Err(err) => return Err(err)
}
guard power >= 0 else {
return Err(
LinearAlgebraError::negative_exponent(
"Matrix::pow requires a non-negative exponent",
),
)
}
Ok(self.unchecked_pow(power))
}
///|
pub fn[T : Semiring] Matrix::unchecked_pow(
self : Matrix[T],
power : Int32,
) -> Matrix[T] {
guard self.is_square() else {
abort("Matrix must be square to calculate powers")
}
guard power >= 0 else {
abort("Matrix::pow requires a non-negative exponent")
}
for state = identity(self.col), exp = power, base = self {
if exp == 0 {
break state
}
if exp == 1 {
break state * base
}
let next_state = if (exp & 1) == 1 { state * base } else { state }
continue next_state, exp >> 1, base * base
}
}
///|
/// Performs Gaussian elimination with partial pivoting to reduce the matrix to
/// reduced row echelon form (RREF).
///
/// This method applies the Gauss-Jordan elimination algorithm, which includes:
///
/// 1. Partial pivoting: selecting the row with the largest absolute value in
/// the current column as the pivot
/// 2. Row swapping to move the pivot to the diagonal position
/// 3. Scaling the pivot row to make the pivot element equal to 1
/// 4. Eliminating all other elements in the current column to make them zero
///
/// The matrix is modified in-place during the elimination process.
///
/// Parameters:
///
/// * `self` : The matrix to be reduced to reduced row echelon form.
///
/// Returns the same matrix instance after performing the row elimination
/// operations.
///
/// Columns whose remaining entries are all zero are skipped. Pivot inversion is
/// only performed after a nonzero pivot has been selected.
///
/// Example:
///
/// ```moonbit nocheck
/// let m = @mutable.Matrix::from_2d_array([
/// [1.0, 2.0, 3.0, 7.0],
/// [1.0, 1.0, 1.0, 2.0],
/// [2.0, 3.0, 3.0, 5.0]
/// ])
/// let result = m.reduce_row_elimination()
/// // Result will be in reduced row echelon form:
/// // |1, 0, 0, 1|
/// // |0, 1, 0, -3|
/// // |0, 0, 1, 4|
/// inspect(result, content="|1, 0, 0, 1|\n|0, 1, 0, -3|\n|0, 0, 1, 4|")
/// ```
///
pub fn[T : Compare + Field + Num + Tolerance] Matrix::reduce_row_elimination(
self : Matrix[T],
) -> Matrix[T] {
let r = self.row
let c = self.col
let data = self.data
let tol = Tolerance::tolerance()
let mut col = 0
for i in 0.. self[max_row][col].abs()
if Num::abs(data[j * c + col]) > Num::abs(data[max_row * c + col]) {
max_row = j
}
}
ignore(self.swap_rows(i, max_row))
let pivot_offset = i * c + col
if Num::abs(data[pivot_offset]) <= tol {
data[pivot_offset] = Zero::zero()
col = col + 1
continue
}
let factor_inv = @lf_alg.Inverse::inv(data[pivot_offset])
let pivot_row_offset = i * c
for k in 0.. Bool {
let tol = Tolerance::tolerance()
self.mul_array_into(x, y)
let mut scale = Zero::zero()
for i in 0.. scale {
scale = candidate
}
}
if scale <= tol {
return false
}
for i in 0.. Bool {
for i in 0.. Matrix[T] {
guard self.row == other.row else {
abort("Matrix::horizontal_combine: dimension mismatch")
}
Matrix::make(self.row, self.col + other.col, fn(i, j) {
if j < self.col {
// self[i][j]
self.data[i * self.col + j]
} else {
// other[i][j - self.col]
other.data[i * other.col + (j - self.col)]
}
})
}
///|
/// Combines two matrices vertically by stacking the second matrix below the
/// first matrix.
///
/// Parameters:
///
/// * `self` : The first matrix to be placed on top.
/// * `other` : The second matrix to be placed below the first matrix.
///
/// Returns a new matrix with the rows of `self` followed by the rows of
/// `other`.
///
/// Panics if the two matrices have different numbers of columns.
///
/// Example:
///
/// ```moonbit nocheck
/// let m1 = Matrix::from_2d_array([[1, 2], [3, 4]])
/// let m2 = Matrix::from_2d_array([[5, 6], [7, 8]])
/// let result = m1.vertical_combine(m2)
/// // Result is a 4x2 matrix: [[1, 2], [3, 4], [5, 6], [7, 8]]
/// inspect(result, content="|1, 2|\n|3, 4|\n|5, 6|\n|7, 8|")
/// ```
///
pub fn[T] Matrix::vertical_combine(
self : Matrix[T],
other : Matrix[T],
) -> Matrix[T] {
guard self.col == other.col else {
abort("Matrix::vertical_combine: dimension mismatch")
}
let self_data = self.data
let other_data = other.data
let data = []
data.push_iter(self_data.iter())
data.push_iter(other_data.iter())
{ row: self.row + other.row, col: self.col, data, }
}
///|
/// Extracts a specific column from the matrix and returns it as an array.
///
/// Parameters:
///
/// * `self` : The matrix from which to extract the column.
/// * `col` : The zero-based index of the column to extract.
///
/// Returns an array containing all elements from the specified column, ordered
/// from top to bottom.
///
/// Panics if `col` is negative or greater than or equal to the number of
/// columns in the matrix.
///
/// Example:
///
/// ```moonbit nocheck
/// let m = @mutable.Matrix::from_2d_array([[1, 2, 3], [4, 5, 6]])
/// let col1 = m.col_to_array(1)
/// inspect(col1, content="[2, 5]")
/// ```
///
pub fn[T] Matrix::col_to_array(self : Matrix[T], col : Int32) -> Array[T] {
let checked_col = self.matrix_checked_col(col)
let row_count = self.row
let col_count = self.col
if row_count == 0 {
return []
}
let data = self.data
let res = Array::make(row_count, data[checked_col])
for i in 1.. Array[T] {
self.data.copy()
}
///|
pub fn[T] Matrix::row_to_array(self : Matrix[T], row : Int32) -> Array[T] {
let row_offset = self.matrix_row_offset(row)
let col_count = self.col
if col_count == 0 {
return []
}
let data = self.data
let res = Array::make(col_count, data[row_offset])
for i in 1.. Array[Array[T]] {
let row = self.row
let arr_2d = []
for i in 0.. Vector[T] {
self.row_to_array(row)
}
///|
/// Extracts a specific column from the matrix and returns it as a Vector.
///
/// Parameters:
///
/// * `self` : The matrix from which to extract the column.
/// * `col` : The zero-based index of the column to extract.
///
/// Returns a Vector containing all elements from the specified column, ordered
/// from top to bottom.
///
/// Example:
///
/// ```moonbit nocheck
/// let m = @mutable.Matrix::from_2d_array([[1, 2, 3], [4, 5, 6]])
/// let col1 = m.col_to_vector(1)
/// // col1 is a Vector containing [2, 5]
/// inspect(col1, content="|2, 5|")
/// ```
///
pub fn[T] Matrix::col_to_vector(self : Matrix[T], col : Int32) -> Vector[T] {
self.col_to_array(col)
}
///|
/// Converts the matrix to a vector by copying its internal array
/// representation.
///
/// Parameters:
///
/// * `self` : The matrix to be converted to a vector.
///
/// Returns a new vector containing all elements of the matrix in row-major
/// order (elements are stored row by row from left to right, top to bottom).
///
/// Example:
///
/// ```moonbit nocheck
/// let m = @mutable.Matrix::from_2d_array([[1, 2, 3], [4, 5, 6]])
/// let vector = m.to_vector()
/// inspect(vector, content="|1, 2, 3, 4, 5, 6|")
/// ```
///
pub fn[T] Matrix::to_vector(self : Matrix[T]) -> Vector[T] {
self.data.copy()
}
///|
/// Calculates the rank of the matrix using row reduction.
///
/// Parameters:
///
/// * `self` : The matrix to get the rank of.
///
/// Returns the rank of the matrix, which is the dimension of the vector space
/// spanned by its rows or columns.
///
/// Example:
///
/// ```moonbit nocheck
/// let m = @mutable.Matrix::from_2d_array([[1.0, 2.0, 3.0], [2.0, 4.0, 6.0], [7.0, 8.0, 9.0]])
/// let rank = m.rank()
/// inspect(rank, content="2") // The rank of the matrix is 2
/// ```
pub fn[T : Compare + Field + Num + Tolerance] Matrix::rank(
self : Matrix[T],
) -> Int32 {
let mut rank = 0
let reduced = self.copy()
let row_count = reduced.row
let col_count = reduced.col
let data = reduced.data
let tol = Tolerance::tolerance()
let mut pivot_col = 0
for pivot_row in 0.. max_abs {
max_abs = candidate_abs
max_row = candidate_row
}
}
if max_abs < tol {
pivot_col += 1
continue
}
reduced.swap_rows(pivot_row, max_row)
let pivot_row_offset = pivot_row * col_count
let pivot = data[pivot_row_offset + pivot_col]
for eliminate_row in (pivot_row + 1).. Result[T, LinearAlgebraError] {
match ensure_square_checked(self) {
Ok(_) => Ok(self.unchecked_trace())
Err(err) => Err(err)
}
}
///|
pub fn[T : AddMonoid] Matrix::unchecked_trace(self : Matrix[T]) -> T {
guard self.is_square() else {
abort("Matrix must be square to calculate trace")
}
let mut sum = Zero::zero()
for i in 0.. Bool {
self.row == self.col
}
///|
/// Make a iterator over the matrix elements.
///
/// Parameters:
/// * `self` : The matrix to iterate over.
///
/// Returns an iterator that yields each element of the matrix in row-major
///
/// Example:
/// ```moonbit nocheck
/// let m = @mutable.Matrix::from_2d_array([[1, 2], [3, 4]])
/// let iter = m.iter()
/// inspect(iter.collect(), content="[1, 2, 3, 4]") // Collects all elements in row-major order
/// ```
pub fn[T] Matrix::iter(self : Matrix[T]) -> Iter[T] {
self.data.iter()
}
///|
/// Creates an iterator over the elements of a specific row in the matrix.
///
/// Parameters:
/// * `self` : The matrix to iterate over.
/// * `row` : The zero-based index of the row to iterate.
///
/// Returns an iterator that yields each element in the specified row from left to right.
///
/// Panics if `row` is negative or greater than or equal to the number of rows.
///
/// Example:
/// ```moonbit nocheck
/// let m = @mutable.Matrix::from_2d_array([[1, 2, 3], [4, 5, 6]])
/// let row_iter = m.iter_row(1)
/// for elem in row_iter {
/// println(elem) // prints: 4, 5, 6
/// }
/// ```
pub fn[T] Matrix::iter_row(self : Matrix[T], row : Int32) -> Iter[T] {
let start = self.matrix_row_offset(row)
let end = start + self.col
self.data[start:end].iter()
}
///|
/// Creates an iterator over the elements of a specific column in the matrix.
///
/// Parameters:
/// * `self` : The matrix to iterate over.
/// * `col` : The zero-based index of the column to iterate.
///
/// Returns an iterator that yields each element in the specified column from top to bottom.
///
/// Panics if `col` is negative or greater than or equal to the number of columns.
///
/// Example:
/// ```moonbit nocheck
/// let m = @mutable.Matrix::from_2d_array([[1, 2, 3], [4, 5, 6]])
/// let col_iter = m.iter_col(1)
/// for elem in col_iter {
/// println(elem) // prints: 2, 5
/// }
/// ```
pub fn[T] Matrix::iter_col(self : Matrix[T], col : Int32) -> Iter[T] {
ignore(self.matrix_checked_col(col))
self.transpose().iter_row(col)
}
///|
/// Computes eigenpairs for symmetric real matrices using the QR algorithm.
///
/// This routine currently supports only symmetric real matrices. General real
/// matrices may require complex eigenvalues and eigenvectors, which are not yet
/// available in this package.
///
/// Parameters:
///
/// * `self` : The square matrix to compute eigenvalues and eigenvectors for.
///
/// Returns a tuple containing:
/// * A vector of eigenvalues.
/// * A matrix where each column is an eigenvector corresponding to an
/// eigenvalue for supported symmetric inputs.
///
/// Panics if the matrix is not square.
///
/// Example:
///
/// ```moonbit nocheck
/// let m = Matrix::from_2d_array([[6.0, -2.0], [-2.0, 9.0]])
/// let (eigenvals, _) = m.eigen()
/// // eigenvals should be close to [5.0, 10.0]
/// // eigenvecs should be close to [[1.0, 0.0], [0.0, 1.0]]
/// let v1_ok = (eigenvals[0] - 5.0).abs() < Tolerance::tolerance() &&
/// (eigenvals[1] - 10.0).abs() < Tolerance::tolerance()
/// let v2_ok = (eigenvals[0] - 10.0).abs() < Tolerance::tolerance() &&
/// (eigenvals[1] - 5.0).abs() < Tolerance::tolerance()
/// assert_true(v1_ok || v2_ok)
/// ```
pub fn[T : Compare + Field + Num + Sqrt + Tolerance] Matrix::eigen(
self : Matrix[T],
) -> (Vector[T], Matrix[T]) {
guard self.is_square() else {
abort("Matrix must be square for eigenvalue computation")
}
guard self.is_symmetric() else {
abort(
"Matrix::eigen currently supports only symmetric real matrices; general real matrices require complex eigenvalue support",
)
}
if self.row == 2 && self.col == 2 {
return self.eigen_2x2()
}
qr_algorithm(self)
}
///|
/// Implements the QR algorithm for computing eigenvalues and eigenvectors.
///
/// This path first reduces the symmetric matrix to tridiagonal form and then
/// applies an implicit symmetric tridiagonal iteration to recover eigenpairs.
fn[T : Compare + Field + Num + Sqrt + Tolerance] qr_algorithm(
matrix : Matrix[T],
) -> (Vector[T], Matrix[T]) {
guard matrix.is_square() else {
abort("qr_algorithm requires a square matrix")
}
guard matrix.is_symmetric() else {
abort(
"qr_algorithm currently supports only symmetric real matrices; general real matrices require complex eigenvalue support",
)
}
let (diagonal, off_diagonal, eigenvectors) = householder_tridiagonalize(
matrix,
)
symmetric_tridiagonal_eigen(diagonal, off_diagonal, eigenvectors)
}
///|
fn[T : Compare + Field + Num + Sqrt + Tolerance] householder_tridiagonalize(
matrix : Matrix[T],
) -> (Array[T], Array[T], Matrix[T]) {
let n = matrix.row
let q = matrix.copy()
let q_data = q.data
let diagonal = Array::make(n, Zero::zero())
let off_diagonal = Array::make(n, Zero::zero())
if n == 0 {
return (diagonal, off_diagonal, q)
}
for i = n - 1; i >= 1; i = i - 1 {
let l = i - 1
let mut h = Zero::zero()
let mut scale = Zero::zero()
if l > 0 {
for k in 0..<(l + 1) {
scale = scale + Num::abs(q_data[i * n + k])
}
if scale == Zero::zero() {
off_diagonal[i] = q_data[i * n + l]
} else {
for k in 0..<(l + 1) {
let idx = i * n + k
q_data[idx] /= scale
h = h + q_data[idx] * q_data[idx]
}
let f = q_data[i * n + l]
let g_abs = Sqrt::sqrt(h)
let g = if f >= Zero::zero() { -g_abs } else { g_abs }
off_diagonal[i] = scale * g
h = h - f * g
q_data[i * n + l] = f - g
let mut f_acc = Zero::zero()
for j in 0..<(l + 1) {
q_data[j * n + i] = q_data[i * n + j] / h
let mut g_acc = Zero::zero()
for k in 0..<(j + 1) {
g_acc = g_acc + q_data[j * n + k] * q_data[i * n + k]
}
for k in (j + 1)..<(l + 1) {
g_acc = g_acc + q_data[k * n + j] * q_data[i * n + k]
}
off_diagonal[j] = g_acc / h
f_acc = f_acc + off_diagonal[j] * q_data[i * n + j]
}
let hh = f_acc / (h + h)
for j in 0..<(l + 1) {
let f_j = q_data[i * n + j]
let g_j = off_diagonal[j] - hh * f_j
off_diagonal[j] = g_j
for k in 0..<(j + 1) {
let idx = j * n + k
q_data[idx] = q_data[idx] -
(f_j * off_diagonal[k] + g_j * q_data[i * n + k])
}
}
}
} else {
off_diagonal[i] = q_data[i * n + l]
}
diagonal[i] = h
}
diagonal[0] = Zero::zero()
off_diagonal[0] = Zero::zero()
for i in 0.. Tolerance::tolerance() && l >= 0 {
for j in 0..<(l + 1) {
let mut g = Zero::zero()
for k in 0..<(l + 1) {
g = g + q_data[i * n + k] * q_data[k * n + j]
}
for k in 0..<(l + 1) {
q_data[k * n + j] = q_data[k * n + j] - g * q_data[k * n + i]
}
}
}
diagonal[i] = q_data[i * n + i]
q_data[i * n + i] = One::one()
if l >= 0 {
for j in 0..<(l + 1) {
q_data[j * n + i] = Zero::zero()
q_data[i * n + j] = Zero::zero()
}
}
}
(diagonal, off_diagonal, q)
}
///|
fn[T : Compare + Field + Num + Sqrt] symmetric_tridiagonal_eigen(
diagonal : Array[T],
off_diagonal : Array[T],
eigenvectors : Matrix[T],
) -> (Vector[T], Matrix[T]) {
let n = diagonal.length()
if n == 0 {
return (Vector::from_array([]), eigenvectors)
}
let d = diagonal
let e = off_diagonal
let z_data = eigenvectors.data
for i in 1..= 60 {
abort("symmetric_tridiagonal_eigen did not converge")
}
iter += 1
let mut g = (d[l + 1] - d[l]) / (two * e[l])
let mut r = Sqrt::sqrt(g * g + One::one())
if g < Zero::zero() {
r = -r
}
g = d[m] - d[l] + e[l] / (g + r)
let mut s = One::one()
let mut c = One::one()
let mut p = Zero::zero()
for i = m - 1; i >= l; i = i - 1 {
let f = s * e[i]
let b = c * e[i]
if Num::abs(f) >= Num::abs(g) {
c = g / f
r = Sqrt::sqrt(c * c + One::one())
e[i + 1] = f * r
s = One::one() / r
c = c * s
} else {
s = f / g
r = Sqrt::sqrt(s * s + One::one())
e[i + 1] = g * r
c = One::one() / r
s = s * c
}
g = d[i + 1] - p
r = (d[i] - g) * s + two * c * b
p = s * r
d[i + 1] = g + p
g = c * r - b
for k in 0.. (Matrix[T], Matrix[T]) {
let m = matrix.row
let n = matrix.col
let q = identity(m)
let r = matrix.copy()
let q_data = q.data
let r_data = r.data
let two = One::one() + One::one()
let tol = Tolerance::tolerance()
let limit = if m < n { m } else { n }
for k in 0..= Zero::zero() { -norm } else { norm }
let v = Array::make(m - k, Zero::zero())
v[0] = r_data[k * n + k] - alpha
for i in (k + 1).. (T, Vector[T])? {
guard self.is_square() else {
abort("Matrix must be square for power method")
}
let n = self.row
if n == 0 {
abort("Matrix::power_method requires a non-empty square matrix")
}
let tol = Tolerance::tolerance()
let result = Array::make(n, Zero::zero())
let x = Array::make(n, Zero::zero())
let y = Array::make(n, Zero::zero())
let ax = Array::make(n, Zero::zero())
guard self.initialize_power_method_vector(x, y) else { return None }
for _ in 0.. residual {
residual = delta
}
}
if residual <= tol {
for i in 0.. Result[Vector[T], LinearAlgebraError] {
let n = self.col
let v_data = vector.0
guard n == v_data.length() else {
return Err(
LinearAlgebraError::dimension_mismatch(
"Matrix and vector dimensions are not compatible for multiplication",
),
)
}
Ok(self.unchecked_mul_vec(vector))
}
///|
pub fn[T : AddMonoid + Mul] Matrix::unchecked_mul_vec(
self : Matrix[T],
vector : Vector[T],
) -> Vector[T] {
let m = self.row
let n = self.col
let v_data = vector.0
guard n == v_data.length() else {
abort("Matrix and vector dimensions are not compatible for multiplication")
}
let res_data = Array::make(m, Zero::zero())
self.mul_array_into(v_data, res_data)
Vector(res_data)
}
///|
fn[T : AddMonoid + Mul] Matrix::mul_array_into(
self : Matrix[T],
v_data : Array[T],
out : Array[T],
) -> Unit {
let m = self.row
let n = self.col
guard n == v_data.length() else {
abort("Matrix and vector dimensions are not compatible for multiplication")
}
guard m == out.length() else {
abort("Output buffer length mismatch for matrix-vector multiplication")
}
let data = self.data
let mut idx = 0
for i = 0; i < m; i = i + 1 {
let mut sum = Zero::zero()
for j = 0; j < n; j = j + 1 {
sum = sum + data[idx] * v_data[j]
idx += 1
}
out[i] = sum
}
}
///|
#warnings("-unused_value")
fn[T : AddMonoid + Mul] Matrix::mul_vec_into(
self : Matrix[T],
vector : Vector[T],
out : Array[T],
) -> Unit {
let v_data = vector.0
self.mul_array_into(v_data, out)
}
///|
/// Computes the eigenpairs of a symmetric 2x2 matrix analytically.
///
/// The eigenvalues are returned in decreasing order; each eigenvector column
/// is scaled so that its entry of largest magnitude is 1.
///
/// Parameters:
/// * `self` : The 2x2 matrix to compute eigenvalues for.
///
/// Returns a vector containing the two eigenvalues.
///
/// Panics if the matrix is not 2x2.
fn[T : Compare + Field + Num + Sqrt + Tolerance] Matrix::eigen_2x2(
self : Matrix[T],
) -> (Vector[T], Matrix[T]) {
let n = self.col
let a = self.data[0 * n + 0]
let b = self.data[0 * n + 1]
let c = self.data[1 * n + 0]
let d = self.data[1 * n + 1]
let two = One::one() + One::one()
let half_diff = (a - d) / two
if half_diff * half_diff + b * c < Zero::zero() &&
Num::abs(b - c) > Tolerance::tolerance() {
abort(
"Matrix::eigen currently requires real eigenvalues; complex eigenvalues require luna complex support",
)
}
// Symmetric case: work with the symmetric part, whose discriminant
// half_diff^2 + off^2 is a sum of squares and needs no threshold.
let off = (b + c) / two
if off == Zero::zero() {
// Diagonal: the eigenvalues are the diagonal entries, exactly.
return if a >= d {
(
Vector::from_array([a, d]),
Matrix::from_array(2, 2, [
One::one(),
Zero::zero(),
Zero::zero(),
One::one(),
]),
)
} else {
(
Vector::from_array([d, a]),
Matrix::from_array(2, 2, [
Zero::zero(),
One::one(),
One::one(),
Zero::zero(),
]),
)
}
}
let mean = (a + d) / two
let abs_diff = Num::abs(half_diff)
let abs_off = Num::abs(off)
let big = if abs_diff > abs_off { abs_diff } else { abs_off }
let radius = if big == Zero::zero() {
Zero::zero()
} else {
let p = half_diff / big
let q = off / big
big * Sqrt::sqrt(p * p + q * q)
}
// Compute the eigenvalue of larger magnitude without cancellation and the
// other one from the determinant.
let det = a * d - off * off
let (l1, l2) = if mean > Zero::zero() {
let l1 = mean + radius
(l1, det / l1)
} else if mean < Zero::zero() {
let l2 = mean - radius
(det / l2, l2)
} else {
(radius, -radius)
}
// Eigenvector of l1: (l1 - d, off) = (half_diff + radius, off) or
// (off, l1 - a) = (off, radius - half_diff); take the form without
// cancellation. The eigenvector of l2 is orthogonal to it.
let (x0, y0) = if half_diff >= Zero::zero() {
(half_diff + radius, off)
} else {
(off, radius - half_diff)
}
let (x, y) = if x0 == Zero::zero() && y0 == Zero::zero() {
(One::one(), Zero::zero())
} else {
(x0, y0)
}
// Scale each column so that its entry of largest magnitude is 1.
let lead1 = if Num::abs(x) >= Num::abs(y) { x } else { y }
let v11 = x / lead1
let v21 = y / lead1
let lead2 = if Num::abs(y) >= Num::abs(x) { y } else { -x }
let v12 = y / lead2
let v22 = -x / lead2
(Vector::from_array([l1, l2]), Matrix::from_array(2, 2, [v11, v12, v21, v22]))
}
///|
pub trait Tolerance {
fn tolerance() -> Self
}
///|
pub impl Tolerance for Double with fn tolerance() -> Double {
0.00000000001
}
///|
pub impl Tolerance for Float with fn tolerance() -> Float {
0.00000000001
}
///|
/// Calculates the determinant of a square matrix.
///
/// This method uses an efficient algorithm based on self decomposition with partial
/// pivoting. It transforms the matrix into an upper triangular form while tracking
/// row swaps. The determinant is then the product of the diagonal elements of
/// the resulting matrix, adjusted by the sign determined by the number of swaps.
/// This approach is numerically stable and has a time complexity of O(n³).
///
/// Parameters:
/// * `self`: The square matrix.
///
/// Returns the determinant of the matrix.
///
/// Panics if the matrix is not square.
///
/// Example:
/// ```moonbit nocheck
/// let m = @mutable.Matrix::from_2d_array([[4.0, 3.0], [6.0, 3.0]])
/// inspect(m.determinant().unwrap(), content="-6")
/// ```
pub fn[T : Compare + Field + Num + Tolerance] Matrix::determinant(
self : Matrix[T],
) -> Result[T, LinearAlgebraError] {
match ensure_square_checked(self) {
Ok(_) => Ok(self.unchecked_determinant())
Err(err) => Err(err)
}
}
///|
pub fn[T : Compare + Field + Num + Tolerance] Matrix::unchecked_determinant(
self : Matrix[T],
) -> T {
guard self.is_square() else {
abort("Matrix must be square to calculate determinant")
}
let n = self.row
if n >= 5 &&
(is_upper_triangular_fast(self) || is_lower_triangular_fast(self)) {
let data = self.data
let mut det = One::one()
for i = 0; i < n; i = i + 1 {
det *= data[i * n + i]
}
return det
}
match n {
0 => One::one()
1 => self.data[0]
2 => self.data[0] * self.data[3] - self.data[1] * self.data[2]
3 => {
let d = self.data
d[0] * (d[4] * d[8] - d[5] * d[7]) -
d[1] * (d[3] * d[8] - d[5] * d[6]) +
d[2] * (d[3] * d[7] - d[4] * d[6])
}
4 => {
let d = self.data
let s01 = d[0] * d[5] - d[1] * d[4]
let s02 = d[0] * d[6] - d[2] * d[4]
let s03 = d[0] * d[7] - d[3] * d[4]
let s12 = d[1] * d[6] - d[2] * d[5]
let s13 = d[1] * d[7] - d[3] * d[5]
let s23 = d[2] * d[7] - d[3] * d[6]
let c01 = d[8] * d[13] - d[9] * d[12]
let c02 = d[8] * d[14] - d[10] * d[12]
let c03 = d[8] * d[15] - d[11] * d[12]
let c12 = d[9] * d[14] - d[10] * d[13]
let c13 = d[9] * d[15] - d[11] * d[13]
let c23 = d[10] * d[15] - d[11] * d[14]
s01 * c23 - s02 * c13 + s03 * c12 + s12 * c03 - s13 * c02 + s23 * c01
}
_ => self.lu_decompose_internal().determinant_internal()
}
}
///|
fn[T : Eq + Zero] is_upper_triangular_fast(matrix : Matrix[T]) -> Bool {
let n = matrix.row
let data = matrix.data
for i = 1; i < n; i = i + 1 {
let row_offset = i * n
for j = 0; j < i; j = j + 1 {
if data[row_offset + j] != Zero::zero() {
return false
}
}
}
true
}
///|
fn[T : Eq + Zero] is_lower_triangular_fast(matrix : Matrix[T]) -> Bool {
let n = matrix.row
let data = matrix.data
for i = 0; i < n; i = i + 1 {
let row_offset = i * n
for j = i + 1; j < n; j = j + 1 {
if data[row_offset + j] != Zero::zero() {
return false
}
}
}
true
}
///|
/// Computes the inverse of a square matrix using LU decomposition with partial pivoting.
///
/// This method factorizes the matrix once and then solves against the identity
/// matrix. If successful, the resulting matrix is the inverse.
///
/// Parameters:
///
/// * `self` : The square matrix to compute the inverse of.
///
/// Returns an `Option[Matrix[T]]` where:
/// * `Some(inverse_matrix)` if the matrix is invertible
/// * `None` if the matrix is singular (non-invertible)
///
/// Panics if the matrix is not square.
///
///
pub fn[T : Compare + Field + Num + Tolerance] Matrix::inverse(
self : Matrix[T],
) -> Result[Matrix[T], LinearAlgebraError] {
match ensure_square_checked(self) {
Ok(_) => ()
Err(err) => return Err(err)
}
match self.unchecked_inverse() {
Some(inverse) => Ok(inverse)
None =>
Err(
LinearAlgebraError::singular_matrix(
"Matrix is singular and cannot be inverted",
),
)
}
}
///|
pub fn[T : Compare + Field + Num + Tolerance] Matrix::unchecked_inverse(
self : Matrix[T],
) -> Matrix[T]? {
guard self.is_square() else {
abort("Matrix must be square to compute inverse")
}
let n = self.row
if n == 0 {
return Some(Matrix::new(0, 0, Zero::zero()))
}
if is_identity_matrix_fast(self) {
return Some(self.copy())
}
if is_diagonal_matrix_fast(self) {
let data = self.data
let out = Matrix::new(n, n, Zero::zero())
let out_data = out.data
let tol = Tolerance::tolerance()
for i = 0; i < n; i = i + 1 {
let idx = i * n + i
let diag = data[idx]
if Num::abs(diag) < tol {
return None
}
out_data[idx] = @lf_alg.Inverse::inv(diag)
}
return Some(out)
}
if is_permutation_matrix_fast(self) {
return Some(self.transpose())
}
let lu = self.lu_decompose_internal()
if lu.singular {
return None
}
lu.solve_identity_internal()
}
///|
/// Checks if a matrix is invertible (non-singular).
///
/// A matrix is invertible if its determinant is non-zero.
///
/// Parameters:
///
/// * `self` : The square matrix to check for invertibility.
///
/// Returns `true` if the matrix is invertible, `false` otherwise.
///
/// Panics if the matrix is not square.
///
/// Example:
///
/// ```moonbit nocheck
/// let m1 = @mutable.Matrix::from_2d_array([
/// [1.0, 2.0],
/// [3.0, 4.0]
/// ])
/// let m2 = @mutable.Matrix::from_2d_array([
/// [1.0, 2.0],
/// [2.0, 4.0] // This is singular (second row is 2 times first row)
/// ])
/// inspect(m1.is_invertible(), content="true")
/// inspect(m2.is_invertible(), content="false")
/// ```
///
pub fn[T : Compare + Field + Num + Tolerance] Matrix::is_invertible(
self : Matrix[T],
) -> Result[Bool, LinearAlgebraError] {
match ensure_square_checked(self) {
Ok(_) => Ok(self.unchecked_is_invertible())
Err(err) => Err(err)
}
}
///|
pub fn[T : Compare + Field + Num + Tolerance] Matrix::unchecked_is_invertible(
self : Matrix[T],
) -> Bool {
guard self.is_square() else {
abort("Matrix must be square to check invertibility")
}
!self.lu_decompose_internal().singular
}
///|
pub fn[T : Compare + Field + Num + Sqrt + Tolerance] Matrix::cholesky_decomposition(
self : Matrix[T],
) -> Matrix[T]? {
if !self.is_symmetric() {
return None
}
let n = self.row
if n == 0 {
return Some(Matrix::new(0, 0, Zero::zero()))
}
if is_identity_matrix_fast(self) {
return Some(self.copy())
}
if is_diagonal_matrix_fast(self) {
let data = self.data
let out = Matrix::new(n, n, Zero::zero())
let out_data = out.data
let tol = Tolerance::tolerance()
for i = 0; i < n; i = i + 1 {
let idx = i * n + i
let diag = data[idx]
if diag <= tol {
return None
}
out_data[idx] = Sqrt::sqrt(diag)
}
return Some(out)
}
let l = Matrix::new(n, n, Zero::zero())
let self_data = self.data
let l_data = l.data
let tol = Tolerance::tolerance()
for i in 0.. Result[T, LinearAlgebraError] {
guard self.row * self.col > 0 else {
return Err(
LinearAlgebraError::empty_matrix(
"Matrix::mean requires at least one element",
),
)
}
Ok(self.unchecked_mean())
}
///|
pub fn[T : Field] Matrix::unchecked_mean(self : Matrix[T]) -> T {
guard self.row * self.col > 0 else {
abort("Matrix::mean requires at least one element")
}
let (sum, count) = self.data
.iter()
.fold(init=(Zero::zero(), Zero::zero()), fn(acc, x) {
let (sum, count) = acc
(sum + x, count + One::one())
})
sum / count
}
///|
/// Calculates the variance of the elements in the matrix.
///
/// Parameters:
///
/// * `self` : The matrix to calculate the variance of.
///
/// Returns the variance.
///
/// Example:
///
/// ```moonbit nocheck
/// let m = @mutable.Matrix::from_2d_array([[1.0, 2.0], [3.0, 4.0]])
/// inspect(m.variance(), content="1.25")
/// ```
///
pub fn[T : Field] Matrix::variance(
self : Matrix[T],
) -> Result[T, LinearAlgebraError] {
guard self.row * self.col > 0 else {
return Err(
LinearAlgebraError::empty_matrix(
"Matrix::variance requires at least one element",
),
)
}
Ok(self.unchecked_variance())
}
///|
pub fn[T : Field] Matrix::unchecked_variance(self : Matrix[T]) -> T {
guard self.row * self.col > 0 else {
abort("Matrix::variance requires at least one element")
}
let m = self.unchecked_mean()
let (sum_sq_diff, count) = self.data
.iter()
.fold(init=(Zero::zero(), Zero::zero()), fn(acc, x) {
let (sum_sq_diff, count) = acc
let diff = x - m
(sum_sq_diff + diff * diff, count + One::one())
})
sum_sq_diff / count
}
///|
/// Calculates the standard deviation of the elements in the matrix.
///
/// Parameters:
///
/// * `self` : The matrix to calculate the standard deviation of.
///
/// Returns the standard deviation.
///
/// Example:
///
/// ```moonbit nocheck
/// let m = @mutable.Matrix::from_2d_array([[1.0, 2.0], [3.0, 4.0]])
/// // sqrt(1.25) ≈ 1.118
///
/// let std = m.std_dev()
/// ```
///
pub fn[T : Field + Sqrt] Matrix::std_dev(
self : Matrix[T],
) -> Result[T, LinearAlgebraError] {
guard self.row * self.col > 0 else {
return Err(
LinearAlgebraError::empty_matrix(
"Matrix::std_dev requires at least one element",
),
)
}
Ok(self.unchecked_std_dev())
}
///|
pub fn[T : Field + Sqrt] Matrix::unchecked_std_dev(self : Matrix[T]) -> T {
guard self.row * self.col > 0 else {
abort("Matrix::std_dev requires at least one element")
}
Sqrt::sqrt(self.unchecked_variance())
}
///|
/// Checks if the matrix is symmetric (A^T = A).
///
/// Parameters:
///
/// * `self` : The matrix to check.
///
/// Returns `true` if symmetric, `false` otherwise.
///
/// Example:
///
/// ```moonbit nocheck
/// let m = @mutable.Matrix::from_2d_array([[1.0, 2.0], [2.0, 1.0]])
/// inspect(m.is_symmetric(), content="true")
/// ```
///
pub fn[T : Compare + Num + Tolerance] Matrix::is_symmetric(
self : Matrix[T],
) -> Bool {
if self.row != self.col {
return false
}
for i = 0; i < self.row; i = i + 1 {
for j = i + 1; j < self.col; j = j + 1 {
// (self[i][j] - self[j][i])
if Num::abs(self.data[i * self.col + j] - self.data[j * self.col + i]) >
Tolerance::tolerance() {
return false
}
}
}
true
}
///|
fn[T : Eq + Zero + One] is_identity_matrix_fast(matrix : Matrix[T]) -> Bool {
if matrix.row != matrix.col {
return false
}
let n = matrix.row
let data = matrix.data
for i = 0; i < n; i = i + 1 {
let row_offset = i * n
for j = 0; j < n; j = j + 1 {
let expected = if i == j { One::one() } else { Zero::zero() }
if data[row_offset + j] != expected {
return false
}
}
}
true
}
///|
fn[T : Eq + Zero] is_diagonal_matrix_fast(matrix : Matrix[T]) -> Bool {
if matrix.row != matrix.col {
return false
}
let n = matrix.row
let data = matrix.data
for i = 0; i < n; i = i + 1 {
let row_offset = i * n
for j = 0; j < n; j = j + 1 {
if i != j && data[row_offset + j] != Zero::zero() {
return false
}
}
}
true
}
///|
fn[T : Eq + Zero + One] is_permutation_matrix_fast(matrix : Matrix[T]) -> Bool {
if matrix.row != matrix.col {
return false
}
let n = matrix.row
let data = matrix.data
for i = 0; i < n; i = i + 1 {
let row_offset = i * n
let mut one_count = 0
for j = 0; j < n; j = j + 1 {
let value = data[row_offset + j]
if value == One::one() {
one_count += 1
} else if value != Zero::zero() {
return false
}
}
if one_count != 1 {
return false
}
}
for j = 0; j < n; j = j + 1 {
let mut one_count = 0
for i = 0; i < n; i = i + 1 {
let value = data[i * n + j]
if value == One::one() {
one_count += 1
}
}
if one_count != 1 {
return false
}
}
true
}
///|
/// Checks if the matrix is positive definite.
///
/// A matrix is positive definite if it is symmetric and all its eigenvalues are positive.
///
/// Parameters:
///
/// * `self` : The matrix to check.
///
/// Returns `true` if positive definite, `false` otherwise.
///
/// Example:
///
/// ```moonbit nocheck
/// let m = @mutable.Matrix::from_2d_array([[2.0, 0.0], [0.0, 2.0]])
/// inspect(m.is_positive_definite(), content="true")
/// ```
///
pub fn[T : Compare + Field + Num + Sqrt + Tolerance] Matrix::is_positive_definite(
self : Matrix[T],
) -> Bool {
match self.cholesky_decomposition() {
Some(_) => true
None => false
}
}
///|
/// Calculates the n-th power of the matrix.
///
/// Parameters:
///
/// * `self` : The matrix to raise to the power.
/// * `n` : The exponent.
///
/// Returns the matrix raised to the power `n`.
///
/// Example:
///
/// ```moonbit nocheck
/// let m = @mutable.Matrix::from_2d_array([[1, 1], [1, 0]])
/// let m2 = m.matrix_power(2)
/// inspect(m2, content="|2, 1|\n|1, 1|")
/// ```
///
pub fn[T : Semiring] Matrix::matrix_power(
self : Matrix[T],
n : Int32,
) -> Result[Matrix[T], LinearAlgebraError] {
self.pow(n)
}
///|
pub fn[T : Semiring] Matrix::unchecked_matrix_power(
self : Matrix[T],
n : Int32,
) -> Matrix[T] {
self.unchecked_pow(n)
}
///|
/// Calculates the Frobenius norm of the matrix.
///
/// Parameters:
///
/// * `self` : The matrix to calculate the norm of.
///
/// Returns the Frobenius norm.
///
/// Example:
///
/// ```moonbit nocheck
/// let m = @mutable.Matrix::from_2d_array([[1.0, 2.0], [3.0, 4.0]])
/// // sqrt(1^2 + 2^2 + 3^2 + 4^2) = sqrt(30) ≈ 5.477
///
/// let norm = m.frobenius_norm()
/// ```
///
pub fn[T : AddMonoid + Mul + Sqrt] Matrix::frobenius_norm(
self : Matrix[T],
) -> T {
let sum_sq = self.data
.iter()
.fold(init=Zero::zero(), fn(acc, x) { acc + x * x })
Sqrt::sqrt(sum_sq)
}
///|
/// Finds the maximum element in the matrix.
///
/// Parameters:
///
/// * `self` : The matrix to search.
///
/// Returns the maximum element.
///
/// Example:
///
/// ```moonbit nocheck
/// let m = @mutable.Matrix::from_2d_array([[1, 5, 3], [2, 8, 1]])
/// inspect(m.max_element(), content="8")
/// ```
///
pub fn[T : Compare] Matrix::max_element(
self : Matrix[T],
) -> Result[T, LinearAlgebraError] {
if self.data.length() == 0 {
return Err(LinearAlgebraError::empty_matrix("Empty matrix"))
}
Ok(self.unchecked_max_element())
}
///|
pub fn[T : Compare] Matrix::unchecked_max_element(self : Matrix[T]) -> T {
if self.data.length() == 0 {
abort("Empty matrix")
}
let mut max_val = self.data[0]
for i = 1; i < self.data.length(); i = i + 1 {
if self.data[i] > max_val {
max_val = self.data[i]
}
}
max_val
}
///|
/// Finds the minimum element in the matrix.
///
/// Parameters:
///
/// * `self` : The matrix to search.
///
/// Returns the minimum element.
///
/// Example:
///
/// ```moonbit nocheck
/// let m = @mutable.Matrix::from_2d_array([[5, 2, 8], [1, 9, 3]])
/// inspect(m.min_element(), content="1")
/// ```
///
pub fn[T : Compare] Matrix::min_element(
self : Matrix[T],
) -> Result[T, LinearAlgebraError] {
if self.data.length() == 0 {
return Err(LinearAlgebraError::empty_matrix("Empty matrix"))
}
Ok(self.unchecked_min_element())
}
///|
pub fn[T : Compare] Matrix::unchecked_min_element(self : Matrix[T]) -> T {
if self.data.length() == 0 {
abort("Empty matrix")
}
let mut min_val = self.data[0]
for i = 1; i < self.data.length(); i = i + 1 {
if self.data[i] < min_val {
min_val = self.data[i]
}
}
min_val
}