Skip to main content

Crate embedded_matrix

Crate embedded_matrix 

Source
Expand description

§embedded-matrix

2×2 and 3×3 f32 matrices for no_std embedded systems.

No default dependencies, no unsafe, and no allocation.

use embedded_matrix::{Matrix2x2, Matrix3x3, MatrixError};

// Matrix multiplication with the * operator
let a = Matrix3x3::new([
    [1.0, 2.0, 3.0],
    [4.0, 5.0, 6.0],
    [7.0, 8.0, 9.0],
]);
let b = Matrix3x3::identity();
assert_eq!(a * b, a);

// Addition, subtraction, scalar multiplication
assert_eq!((a + b) - b, a);
let _double = a * 2.0;

// Matrix × vector
let v = Matrix2x2::identity() * [1.0, 2.0];
assert_eq!(v, [1.0, 2.0]);

// Inversion (Err if singular or non-finite)
match Matrix2x2::new([[2.0, 0.0], [0.0, 4.0]]).inv() {
    Ok(inv) => assert_eq!(inv, Matrix2x2::new([[0.5, 0.0], [0.0, 0.25]])),
    Err(MatrixError::SingularMatrix) => { /* handle error */ }
    Err(e) => panic!("{e}"),
}

§Solving systems

solve(b) solves A·x = b and returns x directly:

use embedded_matrix::Matrix2x2;

let a = Matrix2x2::new([[2.0, 1.0], [1.0, 3.0]]);
let x = a.solve([3.0, 5.0]).unwrap(); // x = [0.8, 1.4]
assert!((x[0] - 0.8).abs() < 1e-6);

§Optional feature: trig

embedded-matrix = { version = "0.3", features = ["trig"] }

Enables the embedded-trig-f32 dependency and adds rotation constructors: Matrix2x2::rotation(angle), Matrix3x3::rotation_x / _y / _z(angle) (angles in radians, right-hand rule). Without this feature, the crate has no dependencies.

§Future ideas (not implemented)

These ideas are not part of the current API; they are noted here for the future:

  • Arbitrary sizes: stack-allocated Matrix<const R: usize, const C: usize> (alias Matrix2x2 = Matrix<2, 2>), with non-square matrix multiplication.
  • LU decomposition with partial pivoting for det, inv, and solve at size n.
  • Cholesky for symmetric positive-definite matrices (covariance matrices).
  • Vector<N> type: dot product, 3D cross product, norm.
  • #[must_use] on arithmetic operations.
  • Cycle benchmarks (DWT counter) and CI builds for embedded targets.

§Singular matrix detection

inv compares |det| against a bound relative to the magnitude of the determinant terms (rather than an absolute constant): a 1e-4 · I matrix remains invertible, while a matrix with large coefficients whose determinant is only rounding noise is correctly rejected.

Structs§

Matrix2x2
A 2×2 f32 matrix stored in row-major order.
Matrix3x3
A 3×3 f32 matrix stored in row-major order.

Enums§

MatrixError
Error returned when a matrix operation is invalid.