embedded_maths/matrix.rs
1// SPDX-License-Identifier: GPL-2.0-or-later
2//! 2x2 and 3x3 `f32` matrices for `no_std` embedded systems,
3//! powered by `embedded-matrix`.
4//!
5//! Provides `Matrix2x2` and `Matrix3x3` with native operators (`+`, `-`, `*`,
6//! unary `-`, matrix-vector multiplication, `+=`, `-=`, `*=`), determinant,
7//! trace, transpose, inversion (`inv`), and linear system solving (`solve`)
8//! without heap allocation, `libm`, or `unsafe`.
9//!
10//! # Behavior & Notes
11//!
12//! | Operation / Input | Behavior |
13//! |-------------------|----------|
14//! | `Matrix2x2::new` / `Matrix3x3::new` | Builds from row-major `[[f32; N]; N]` (`identity`, `zero`, `from_diagonal`) |
15//! | `inv()` | Returns `Result<M, MatrixError>` using a scale-relative singularity check |
16//! | `solve(b)` | Solves `A * x = b` -> `Result<[f32; N], MatrixError>` |
17//! | `rotation` / `rotation_x/y/z` | Available when the `trig` feature is enabled on `embedded-matrix` |
18//! | Singular matrix | Returns `Err(MatrixError::SingularMatrix)` |
19//! | `NaN`, `±Infinity`, or overflow | Returns `Err(MatrixError::NonFiniteValue)` |
20
21pub use embedded_matrix::{Matrix2x2, Matrix3x3, MatrixError};
22
23/// Inverts a 2x2 matrix.
24pub fn inv_2x2(m: Matrix2x2) -> Result<Matrix2x2, MatrixError> {
25 m.inv()
26}
27
28/// Inverts a 3x3 matrix.
29pub fn inv_3x3(m: Matrix3x3) -> Result<Matrix3x3, MatrixError> {
30 m.inv()
31}
32
33/// Solves a 2x2 linear system `A * x = b`.
34pub fn solve_2x2(a: Matrix2x2, b: [f32; 2]) -> Result<[f32; 2], MatrixError> {
35 a.solve(b)
36}
37
38/// Solves a 3x3 linear system `A * x = b`.
39pub fn solve_3x3(a: Matrix3x3, b: [f32; 3]) -> Result<[f32; 3], MatrixError> {
40 a.solve(b)
41}
42
43#[cfg(test)]
44mod tests {
45 use super::*;
46
47 #[test]
48 fn ops_inv_and_solve() {
49 let a = Matrix2x2::new([[1.0, 2.0], [3.0, 4.0]]);
50 assert_eq!(a.det(), -2.0);
51 let inv = inv_2x2(a).unwrap();
52 let prod = a * inv;
53 assert!(prod.approx_eq(&Matrix2x2::identity(), 1e-5));
54
55 let m3 = Matrix3x3::new([[1.0, 2.0, 3.0], [0.0, 1.0, 4.0], [5.0, 6.0, 0.0]]);
56 let x = solve_3x3(m3, [1.0, 2.0, 3.0]).unwrap();
57 let rhs = m3 * x;
58 assert!((rhs[0] - 1.0).abs() < 1e-4);
59 assert!((rhs[1] - 2.0).abs() < 1e-4);
60 assert!((rhs[2] - 3.0).abs() < 1e-4);
61 }
62
63 #[test]
64 fn error_cases() {
65 let singular = Matrix2x2::new([[1.0, 2.0], [2.0, 4.0]]);
66 assert_eq!(inv_2x2(singular), Err(MatrixError::SingularMatrix));
67
68 let nan_mat = Matrix2x2::new([[f32::NAN, 0.0], [0.0, 1.0]]);
69 assert_eq!(inv_2x2(nan_mat), Err(MatrixError::NonFiniteValue));
70 }
71}