Skip to main content

embedded_matrix/
lib.rs

1// Copyright (C) 2026 Jorge Andre Castro
2//
3// This program is free software: you can redistribute it and/or modify it
4// under the terms of the GNU General Public License as published by the
5// Free Software Foundation, either version 2 of the License, or
6// any later version.
7
8//! # embedded-matrix
9//!
10//! 2×2 and 3×3 `f32` matrices for `no_std` embedded systems.
11//!
12//! No default dependencies, no `unsafe`, and no allocation.
13//!
14//! ```rust
15//! use embedded_matrix::{Matrix2x2, Matrix3x3, MatrixError};
16//!
17//! // Matrix multiplication with the * operator
18//! let a = Matrix3x3::new([
19//!     [1.0, 2.0, 3.0],
20//!     [4.0, 5.0, 6.0],
21//!     [7.0, 8.0, 9.0],
22//! ]);
23//! let b = Matrix3x3::identity();
24//! assert_eq!(a * b, a);
25//!
26//! // Addition, subtraction, scalar multiplication
27//! assert_eq!((a + b) - b, a);
28//! let _double = a * 2.0;
29//!
30//! // Matrix × vector
31//! let v = Matrix2x2::identity() * [1.0, 2.0];
32//! assert_eq!(v, [1.0, 2.0]);
33//!
34//! // Inversion (Err if singular or non-finite)
35//! match Matrix2x2::new([[2.0, 0.0], [0.0, 4.0]]).inv() {
36//!     Ok(inv) => assert_eq!(inv, Matrix2x2::new([[0.5, 0.0], [0.0, 0.25]])),
37//!     Err(MatrixError::SingularMatrix) => { /* handle error */ }
38//!     Err(e) => panic!("{e}"),
39//! }
40//! ```
41//!
42//! ## Solving systems
43//!
44//! `solve(b)` solves `A·x = b` and returns `x` directly:
45//!
46//! ```rust
47//! use embedded_matrix::Matrix2x2;
48//!
49//! let a = Matrix2x2::new([[2.0, 1.0], [1.0, 3.0]]);
50//! let x = a.solve([3.0, 5.0]).unwrap(); // x = [0.8, 1.4]
51//! assert!((x[0] - 0.8).abs() < 1e-6);
52//! ```
53//!
54//! ## Optional feature: `trig`
55//!
56//! ```toml
57//! embedded-matrix = { version = "0.3", features = ["trig"] }
58//! ```
59//!
60//! Enables the `embedded-trig-f32` dependency and adds rotation constructors:
61//! `Matrix2x2::rotation(angle)`, `Matrix3x3::rotation_x / _y / _z(angle)`
62//! (angles in radians, right-hand rule). Without this feature, the crate
63//! has **no dependencies**.
64//!
65//! ## Future ideas (not implemented)
66//!
67//! These ideas are not part of the current API; they are noted here
68//! for the future:
69//!
70//! - **Arbitrary sizes**: stack-allocated `Matrix<const R: usize, const C: usize>`
71//!   (alias `Matrix2x2 = Matrix<2, 2>`), with non-square matrix multiplication.
72//! - **LU decomposition** with partial pivoting for `det`, `inv`, and `solve`
73//!   at size n.
74//! - **Cholesky** for symmetric positive-definite matrices
75//!   (covariance matrices).
76//! - **`Vector<N>` type**: dot product, 3D cross product, norm.
77//! - **`#[must_use]`** on arithmetic operations.
78//! - **Cycle benchmarks** (DWT counter) and CI builds for embedded targets.
79//!
80//! ## Singular matrix detection
81//!
82//! `inv` compares `|det|` against a bound **relative** to the magnitude of the
83//! determinant terms (rather than an absolute constant): a `1e-4 · I` matrix
84//! remains invertible, while a matrix with large coefficients whose
85//! determinant is only rounding noise is correctly rejected.
86
87#![no_std]
88#![forbid(unsafe_code)]
89#![deny(missing_docs)]
90
91mod error;
92mod matrix2x2;
93mod matrix3x3;
94
95pub use error::MatrixError;
96pub use matrix2x2::Matrix2x2;
97pub use matrix3x3::Matrix3x3;
98
99/// Relative threshold: `|det| <= SINGULAR_REL * bound` ⇒ singular matrix.
100/// `bound` is the sum of the absolute values of the determinant terms.
101const SINGULAR_REL: f32 = 8.0 * f32::EPSILON;
102
103/// Validates a determinant before inversion.
104///
105/// `bound`: sum of the absolute values of the terms making up `det`
106/// (the scale of the expected rounding error in `det`).
107#[inline]
108pub(crate) fn check_det(det: f32, bound: f32) -> Result<(), MatrixError> {
109    if !det.is_finite() || !bound.is_finite() {
110        return Err(MatrixError::NonFiniteValue);
111    }
112    if det.abs() <= SINGULAR_REL * bound {
113        Err(MatrixError::SingularMatrix)
114    } else {
115        Ok(())
116    }
117}