viva_math/matrix
Small dense matrices (2×2, 3×3, 4×4) and a generic MatN.
Scope: geometry, dynamics, small-system linear algebra. For batched
or large-scale work (GEMM, BLAS, eigendecomposition) use viva_tensor,
which dispatches to MKL/CUDA.
Conventions
- Row-major storage in the generic
MatN(rows × cols). - Fixed-size matrices use named fields
m11..mNN. - All constructors clamp to safe values where appropriate.
Types
pub type Mat2 {
Mat2(m11: Float, m12: Float, m21: Float, m22: Float)
}
Constructors
-
Mat2(m11: Float, m12: Float, m21: Float, m22: Float)
pub type Mat3 {
Mat3(
m11: Float,
m12: Float,
m13: Float,
m21: Float,
m22: Float,
m23: Float,
m31: Float,
m32: Float,
m33: Float,
)
}
Constructors
-
Mat3( m11: Float, m12: Float, m13: Float, m21: Float, m22: Float, m23: Float, m31: Float, m32: Float, m33: Float, )
Values
pub fn mat2_eigenvalues(m: Mat2) -> Result(#(Float, Float), Nil)
Real eigenvalues of a 2×2 matrix via the characteristic quadratic.
λ² - tr(M)·λ + det(M) = 0 → λ = (tr ± √(tr² - 4·det)) / 2.
Returns Error for matrices with non-real eigenvalues (negative
discriminant). For symmetric matrices the discriminant is always
non-negative, so this always succeeds.
pub fn mat2_identity() -> Mat2
pub fn mat3_determinant(m: Mat3) -> Float
Determinant via cofactor expansion along the first row.
pub fn mat3_identity() -> Mat3
pub fn mat3_inverse(m: Mat3) -> Result(Mat3, Nil)
Inverse of a 3×3 matrix via adjugate / determinant.
Errors when the matrix is singular or ill-conditioned: the threshold is
|det| < ε · ‖M‖_F³ where ε ≈ machine epsilon. Pure det == 0.0 is too
permissive — matrices with det = 1e-20 would still pass and produce
catastrophic blow-up after division.
pub fn mat3_mul_vec3(m: Mat3, v: vector.Vec3) -> vector.Vec3
Matrix × Vec3 product.
pub fn mat3_symmetric_eigenvalues(
m: Mat3,
) -> Result(#(Float, Float, Float), Nil)
Real eigenvalues of a symmetric 3×3 matrix via Smith’s trigonometric closed form. The matrix must be (numerically) symmetric.
Algorithm: characteristic cubic det(M - λI) = 0 in the form λ³ - tr·λ² + … Then shift by p = tr/3 and solve the depressed cubic using trigonometric substitution.
Reference: Smith (1961) “Eigenvalues of a Symmetric 3×3 Matrix”.
pub fn mat3_trace(m: Mat3) -> Float
pub fn mat4_identity() -> Mat4
pub fn mat4_translation(tx: Float, ty: Float, tz: Float) -> Mat4
Translation homogeneous transform.
pub fn matn_from_rows(
rows: List(List(Float)),
) -> Result(MatN, Nil)
Build a MatN from a row-major list of rows.
Errors if rows is empty, has empty rows, or rows of inconsistent length.
pub fn matn_mul(a: MatN, b: MatN) -> Result(MatN, Nil)
Matrix product A·B. Errors on shape mismatch.
pub fn matn_mul_vec(
m: MatN,
v: List(Float),
) -> Result(List(Float), Nil)
Matrix × column-vector product. Returns the resulting vector as a list.
pub fn matn_trace(m: MatN) -> Result(Float, Nil)
Trace (sum of diagonal). Defined for square matrices.