multicalc 0.9.0

Math for real-time embedded systems, in stable no_std Rust: state estimation, control, kinematics, Lie groups, autodiff, and linear algebra — from 64-bit servers to bare-metal microcontrollers
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
//! Fixed-size, stack-allocated matrix.

use core::ops::{Add, AddAssign, Index, IndexMut, Mul, Neg, Sub, SubAssign};

use crate::error::LinalgError;
use crate::linear_algebra::Vector;
use crate::scalar::Numeric;

/// A `ROWS`×`COLS` matrix stored inline on the stack in row-major order.
///
/// ```
/// use multicalc::linear_algebra::{Matrix, Vector};
/// let a = Matrix::new([[1.0, 2.0], [3.0, 4.0]]);
/// let b = Matrix::new([[5.0, 6.0], [7.0, 8.0]]);
///
/// assert_eq!(a[(0, 1)], 2.0);
/// assert_eq!(a.get(0, 1), Some(&2.0));
/// assert_eq!((a + b).into_array(), [[6.0, 8.0], [10.0, 12.0]]);
/// assert_eq!((b - a).into_array(), [[4.0, 4.0], [4.0, 4.0]]);
/// assert_eq!((-a).into_array(), [[-1.0, -2.0], [-3.0, -4.0]]);
/// assert_eq!((a * 2.0).into_array(), [[2.0, 4.0], [6.0, 8.0]]);
/// assert_eq!((a * b).into_array(), [[19.0, 22.0], [43.0, 50.0]]);
/// assert_eq!(a * Vector::new([1.0, 1.0]), Vector::new([3.0, 7.0]));
/// ```
#[repr(C)]
#[derive(Debug, Clone, Copy, PartialEq)]
#[must_use]
pub struct Matrix<const ROWS: usize, const COLS: usize, T = f64> {
    data: [[T; COLS]; ROWS],
}

impl<const ROWS: usize, const COLS: usize, T> Matrix<ROWS, COLS, T> {
    /// Wraps a row-major array of rows into a matrix.
    #[inline]
    pub const fn new(data: [[T; COLS]; ROWS]) -> Self {
        Matrix { data }
    }

    /// Builds a matrix by calling `f` with each `(row, column)` index.
    ///
    /// ```
    /// use multicalc::linear_algebra::Matrix;
    /// let m = Matrix::<2, 2>::from_fn(|r, c| (r * 2 + c) as f64);
    /// assert_eq!(m.into_array(), [[0.0, 1.0], [2.0, 3.0]]);
    /// ```
    #[inline]
    pub fn from_fn(mut f: impl FnMut(usize, usize) -> T) -> Self {
        Matrix {
            data: core::array::from_fn(|r| core::array::from_fn(|c| f(r, c))),
        }
    }

    // Crate-internal panic path (also used by Index). Public: prefer `[]`; use `get` when fallible.
    #[inline]
    #[track_caller]
    pub(crate) fn at(&self, row: usize, col: usize) -> &T {
        #[allow(clippy::indexing_slicing)]
        &self.data[row][col]
    }

    #[inline]
    #[track_caller]
    pub(crate) fn at_mut(&mut self, row: usize, col: usize) -> &mut T {
        #[allow(clippy::indexing_slicing)]
        &mut self.data[row][col]
    }

    /// Borrows the rows.
    ///
    /// ```
    /// use multicalc::linear_algebra::Matrix;
    /// assert_eq!(Matrix::new([[1.0, 2.0]]).as_slice_rows(), &[[1.0, 2.0]]);
    /// ```
    #[inline]
    #[must_use]
    pub const fn as_slice_rows(&self) -> &[[T; COLS]; ROWS] {
        &self.data
    }

    /// Borrows the rows mutably.
    ///
    /// ```
    /// use multicalc::linear_algebra::Matrix;
    /// let mut m = Matrix::new([[1.0, 2.0]]);
    /// m.as_mut_slice_rows()[0][1] = 9.0;
    /// assert_eq!(m[(0, 1)], 9.0);
    /// ```
    #[inline]
    pub fn as_mut_slice_rows(&mut self) -> &mut [[T; COLS]; ROWS] {
        &mut self.data
    }

    /// Returns a reference to entry `(row, col)`, or `None` if out of range.
    ///
    /// ```
    /// use multicalc::linear_algebra::Matrix;
    /// let m = Matrix::new([[1.0, 2.0], [3.0, 4.0]]);
    /// assert_eq!(m.get(1, 0), Some(&3.0));
    /// assert_eq!(m.get(2, 0), None);
    /// ```
    #[inline]
    #[must_use]
    pub fn get(&self, row: usize, col: usize) -> Option<&T> {
        self.data.get(row).and_then(|r| r.get(col))
    }

    /// Returns a mutable reference to entry `(row, col)`, or `None` if out of range.
    ///
    /// ```
    /// use multicalc::linear_algebra::Matrix;
    /// let mut m = Matrix::new([[1.0, 2.0], [3.0, 4.0]]);
    /// if let Some(x) = m.get_mut(0, 1) {
    ///     *x = 7.0;
    /// }
    /// assert_eq!(m.get(0, 1), Some(&7.0));
    /// ```
    #[inline]
    pub fn get_mut(&mut self, row: usize, col: usize) -> Option<&mut T> {
        self.data.get_mut(row).and_then(|r| r.get_mut(col))
    }

    /// Consumes the matrix, returning its rows.
    #[inline]
    #[must_use]
    pub fn into_array(self) -> [[T; COLS]; ROWS] {
        self.data
    }
}

impl<const ROWS: usize, const COLS: usize, T: Copy> Matrix<ROWS, COLS, T> {
    /// Builds a matrix from a row-major slice, or `None` if `slice.len()` is not `ROWS * COLS`.
    ///
    /// ```
    /// use multicalc::linear_algebra::Matrix;
    /// assert!(Matrix::<2, 2>::try_from_row_slice(&[1.0, 2.0, 3.0, 4.0]).is_some());
    /// assert!(Matrix::<2, 2>::try_from_row_slice(&[1.0, 2.0, 3.0]).is_none());
    /// ```
    #[inline]
    #[must_use]
    pub fn try_from_row_slice(slice: &[T]) -> Option<Self> {
        // In-bounds by construction: `r < ROWS`, `c < COLS`, and the length was just checked.
        #[allow(clippy::indexing_slicing)]
        (slice.len() == ROWS * COLS).then(|| Self::from_fn(|r, c| slice[r * COLS + c]))
    }

    /// Copies row `r`, or `None` if `r >= ROWS`.
    ///
    /// ```
    /// use multicalc::linear_algebra::{Matrix, Vector};
    /// let m = Matrix::new([[1.0, 2.0], [3.0, 4.0]]);
    /// assert_eq!(m.try_row(1), Some(Vector::new([3.0, 4.0])));
    /// assert_eq!(m.try_row(2), None);
    /// ```
    #[inline]
    #[must_use]
    pub fn try_row(&self, r: usize) -> Option<Vector<COLS, T>> {
        self.data.get(r).copied().map(Vector::new)
    }

    /// Copies column `c`, or `None` if `c >= COLS`.
    ///
    /// ```
    /// use multicalc::linear_algebra::{Matrix, Vector};
    /// let m = Matrix::new([[1.0, 2.0], [3.0, 4.0]]);
    /// assert_eq!(m.try_column(1), Some(Vector::new([2.0, 4.0])));
    /// assert_eq!(m.try_column(2), None);
    /// let empty: Matrix<0, 3> = Matrix::zeros();
    /// assert_eq!(empty.try_column(0), Some(Vector::<0>::zeros()));
    /// assert_eq!(empty.try_column(3), None);
    /// ```
    #[inline]
    #[must_use]
    pub fn try_column(&self, c: usize) -> Option<Vector<ROWS, T>> {
        (c < COLS).then(|| Vector::from_fn(|r| self.data[r][c]))
    }
}

impl<const ROWS: usize, const COLS: usize, T: Numeric> Matrix<ROWS, COLS, T> {
    /// The zero matrix.
    ///
    /// ```
    /// use multicalc::linear_algebra::Matrix;
    /// let m: Matrix<2, 3> = Matrix::zeros();
    /// assert_eq!(m.into_array(), [[0.0, 0.0, 0.0], [0.0, 0.0, 0.0]]);
    /// ```
    #[inline]
    pub fn zeros() -> Self {
        Matrix::from_fn(|_, _| T::ZERO)
    }

    /// Multiplies every element by `scalar`.
    ///
    /// ```
    /// use multicalc::linear_algebra::Matrix;
    /// let m = Matrix::new([[1.0, 2.0]]);
    /// let factor = 3.0;
    /// assert_eq!(m.scale(factor).into_array(), [[3.0, 6.0]]);
    /// ```
    #[inline]
    pub fn scale(self, scalar: T) -> Self {
        Matrix::from_fn(|r, c| self[(r, c)] * scalar)
    }

    /// The transpose, with rows and columns swapped.
    ///
    /// ```
    /// use multicalc::linear_algebra::Matrix;
    /// let m = Matrix::new([[1.0, 2.0, 3.0]]);
    /// assert_eq!(m.transpose().into_array(), [[1.0], [2.0], [3.0]]);
    /// ```
    #[inline]
    pub fn transpose(self) -> Matrix<COLS, ROWS, T> {
        Matrix::from_fn(|r, c| self[(c, r)])
    }

    /// Returns `true` when every entry is neither infinite nor NaN.
    ///
    /// ```
    /// use multicalc::linear_algebra::Matrix;
    /// assert!(Matrix::new([[1.0, -2.0], [3.0, 4.0]]).is_finite());
    /// assert!(!Matrix::new([[1.0, f64::NAN], [3.0, 4.0]]).is_finite());
    /// ```
    #[inline]
    #[must_use]
    pub fn is_finite(self) -> bool {
        self.data.iter().flatten().all(|x| x.is_finite())
    }

    /// Largest absolute entry; used to scale near-singularity checks.
    #[inline]
    #[must_use]
    fn max_abs(self) -> T {
        let mut best = T::ZERO;
        for row in &self.data {
            for x in row {
                best = best.max(x.abs());
            }
        }
        best
    }

    /// `true` when `|det|` is at or below `EPSILON * n * scale^n`.
    #[inline]
    #[must_use]
    fn det_near_singular(det: T, scale: T, n: usize) -> bool {
        det.abs() <= T::EPSILON * T::from_usize(n) * scale.powi(n as i32)
    }
}

impl<const N: usize, T: Numeric> Matrix<N, N, T> {
    /// The `N`×`N` identity matrix.
    ///
    /// ```
    /// use multicalc::linear_algebra::Matrix;
    /// let i: Matrix<3, 3> = Matrix::identity();
    /// assert_eq!(i.into_array(), [[1.0, 0.0, 0.0], [0.0, 1.0, 0.0], [0.0, 0.0, 1.0]]);
    /// ```
    #[inline]
    pub fn identity() -> Self {
        Matrix::from_fn(|r, c| if r == c { T::ONE } else { T::ZERO })
    }

    /// The determinant.
    ///
    /// Sizes up to 4×4 use a closed form; larger ones use an LU factorization. A matrix whose
    /// factorization breaks down on an all-zero pivot column is exactly singular, so its
    /// determinant is zero.
    ///
    /// ```
    /// use multicalc::linear_algebra::Matrix;
    /// assert_eq!(Matrix::new([[1.0, 2.0], [3.0, 4.0]]).determinant(), -2.0);
    /// ```
    #[inline]
    #[must_use]
    pub fn determinant(self) -> T {
        match N {
            0 => T::ONE,
            1 => self.data[0][0],
            2 => self.determinant_2x2(),
            3 => self.determinant_3x3(),
            4 => self.determinant_4x4(),
            _ => match self.lu() {
                Ok(factorization) => factorization.determinant(),
                Err(_) => T::ZERO,
            },
        }
    }

    /// The inverse, or [`LinalgError::Singular`] if the matrix is singular or near-singular.
    ///
    /// Sizes up to 4×4 use a closed form and reject a matrix whose `|det|` is at or below an
    /// `EPSILON`-scaled threshold. Larger ones use an LU factorization and reject one whose
    /// smallest pivot is negligible against its largest.
    ///
    /// ```
    /// use multicalc::linear_algebra::Matrix;
    /// let m: Matrix<2, 2> = Matrix::new([[4.0, 7.0], [2.0, 6.0]]);
    /// let p = (m * m.inverse().unwrap());
    /// assert!((p[(0, 0)] - 1.0).abs() < 1e-12 && (p[(1, 1)] - 1.0).abs() < 1e-12);
    /// assert!(Matrix::<2, 2>::new([[1.0, 2.0], [2.0, 4.0]]).inverse().is_err());
    /// ```
    #[inline]
    pub fn inverse(self) -> Result<Self, LinalgError> {
        match N {
            0 => Ok(self),
            1 => self.inverse_1x1(),
            2 => self.inverse_2x2(),
            3 => self.inverse_3x3(),
            4 => self.inverse_4x4(),
            _ => self.inverse_lu(),
        }
    }

    #[inline]
    fn inverse_1x1(mut self) -> Result<Self, LinalgError> {
        let value = self.data[0][0];
        if Self::det_near_singular(value, value.abs(), 1) {
            return Err(LinalgError::Singular);
        }
        self.data[0][0] = T::ONE / value;
        Ok(self)
    }

    #[inline]
    fn determinant_2x2(self) -> T {
        self.data[0][0] * self.data[1][1] - self.data[0][1] * self.data[1][0]
    }

    #[inline]
    fn inverse_2x2(mut self) -> Result<Self, LinalgError> {
        let determinant = self.determinant_2x2();
        if Self::det_near_singular(determinant, self.max_abs(), 2) {
            return Err(LinalgError::Singular);
        }
        let scale = T::ONE / determinant;
        let m = self.data;
        self.data[0][0] = m[1][1] * scale;
        self.data[0][1] = -m[0][1] * scale;
        self.data[1][0] = -m[1][0] * scale;
        self.data[1][1] = m[0][0] * scale;
        Ok(self)
    }

    #[inline]
    fn determinant_3x3(self) -> T {
        let m = self.data;
        m[0][0] * (m[1][1] * m[2][2] - m[1][2] * m[2][1])
            - m[0][1] * (m[1][0] * m[2][2] - m[1][2] * m[2][0])
            + m[0][2] * (m[1][0] * m[2][1] - m[1][1] * m[2][0])
    }

    #[inline]
    fn inverse_3x3(mut self) -> Result<Self, LinalgError> {
        let determinant = self.determinant_3x3();
        if Self::det_near_singular(determinant, self.max_abs(), 3) {
            return Err(LinalgError::Singular);
        }
        let scale = T::ONE / determinant;
        let m = self.data;
        let adjugate = [
            [
                m[1][1] * m[2][2] - m[1][2] * m[2][1],
                m[0][2] * m[2][1] - m[0][1] * m[2][2],
                m[0][1] * m[1][2] - m[0][2] * m[1][1],
            ],
            [
                m[1][2] * m[2][0] - m[1][0] * m[2][2],
                m[0][0] * m[2][2] - m[0][2] * m[2][0],
                m[0][2] * m[1][0] - m[0][0] * m[1][2],
            ],
            [
                m[1][0] * m[2][1] - m[1][1] * m[2][0],
                m[0][1] * m[2][0] - m[0][0] * m[2][1],
                m[0][0] * m[1][1] - m[0][1] * m[1][0],
            ],
        ];
        for (row, entries) in adjugate.iter().enumerate() {
            for (column, &entry) in entries.iter().enumerate() {
                self.data[row][column] = entry * scale;
            }
        }
        Ok(self)
    }

    /// The six 2×2 minors of the top row pair (`top`) and the bottom row pair (`bottom`),
    /// indexed by column pair `01, 02, 03, 12, 13, 23`. Both the 4×4 determinant and its
    /// adjugate are built from these, so they are computed once and shared.
    #[inline]
    fn row_pair_minors(self) -> ([T; 6], [T; 6]) {
        let m = self.data;
        let top = [
            m[0][0] * m[1][1] - m[0][1] * m[1][0],
            m[0][0] * m[1][2] - m[0][2] * m[1][0],
            m[0][0] * m[1][3] - m[0][3] * m[1][0],
            m[0][1] * m[1][2] - m[0][2] * m[1][1],
            m[0][1] * m[1][3] - m[0][3] * m[1][1],
            m[0][2] * m[1][3] - m[0][3] * m[1][2],
        ];
        let bottom = [
            m[2][0] * m[3][1] - m[2][1] * m[3][0],
            m[2][0] * m[3][2] - m[2][2] * m[3][0],
            m[2][0] * m[3][3] - m[2][3] * m[3][0],
            m[2][1] * m[3][2] - m[2][2] * m[3][1],
            m[2][1] * m[3][3] - m[2][3] * m[3][1],
            m[2][2] * m[3][3] - m[2][3] * m[3][2],
        ];
        (top, bottom)
    }

    #[inline]
    fn determinant_4x4(self) -> T {
        let (top, bottom) = self.row_pair_minors();
        top[0] * bottom[5] - top[1] * bottom[4] + top[2] * bottom[3] + top[3] * bottom[2]
            - top[4] * bottom[1]
            + top[5] * bottom[0]
    }

    #[inline]
    fn inverse_4x4(mut self) -> Result<Self, LinalgError> {
        let (top, bottom) = self.row_pair_minors();
        let determinant =
            top[0] * bottom[5] - top[1] * bottom[4] + top[2] * bottom[3] + top[3] * bottom[2]
                - top[4] * bottom[1]
                + top[5] * bottom[0];
        if Self::det_near_singular(determinant, self.max_abs(), 4) {
            return Err(LinalgError::Singular);
        }
        let scale = T::ONE / determinant;
        let m = self.data;
        let adjugate = [
            [
                m[1][1] * bottom[5] - m[1][2] * bottom[4] + m[1][3] * bottom[3],
                -m[0][1] * bottom[5] + m[0][2] * bottom[4] - m[0][3] * bottom[3],
                m[3][1] * top[5] - m[3][2] * top[4] + m[3][3] * top[3],
                -m[2][1] * top[5] + m[2][2] * top[4] - m[2][3] * top[3],
            ],
            [
                -m[1][0] * bottom[5] + m[1][2] * bottom[2] - m[1][3] * bottom[1],
                m[0][0] * bottom[5] - m[0][2] * bottom[2] + m[0][3] * bottom[1],
                -m[3][0] * top[5] + m[3][2] * top[2] - m[3][3] * top[1],
                m[2][0] * top[5] - m[2][2] * top[2] + m[2][3] * top[1],
            ],
            [
                m[1][0] * bottom[4] - m[1][1] * bottom[2] + m[1][3] * bottom[0],
                -m[0][0] * bottom[4] + m[0][1] * bottom[2] - m[0][3] * bottom[0],
                m[3][0] * top[4] - m[3][1] * top[2] + m[3][3] * top[0],
                -m[2][0] * top[4] + m[2][1] * top[2] - m[2][3] * top[0],
            ],
            [
                -m[1][0] * bottom[3] + m[1][1] * bottom[1] - m[1][2] * bottom[0],
                m[0][0] * bottom[3] - m[0][1] * bottom[1] + m[0][2] * bottom[0],
                -m[3][0] * top[3] + m[3][1] * top[1] - m[3][2] * top[0],
                m[2][0] * top[3] - m[2][1] * top[1] + m[2][2] * top[0],
            ],
        ];
        for (row, entries) in adjugate.iter().enumerate() {
            for (column, &entry) in entries.iter().enumerate() {
                self.data[row][column] = entry * scale;
            }
        }
        Ok(self)
    }

    #[inline]
    fn inverse_lu(self) -> Result<Self, LinalgError> {
        let factorization = self.lu()?;
        Ok(factorization.inverse())
    }
}

impl<const ROWS: usize, const COLS: usize, T> From<[[T; COLS]; ROWS]> for Matrix<ROWS, COLS, T> {
    #[inline]
    fn from(data: [[T; COLS]; ROWS]) -> Self {
        Matrix { data }
    }
}

impl<const ROWS: usize, const COLS: usize, T> Index<(usize, usize)> for Matrix<ROWS, COLS, T> {
    type Output = T;

    /// Panics if `(row, col)` is out of range. Use [`Self::get`] when the index may be invalid.
    #[inline]
    #[track_caller]
    fn index(&self, (row, col): (usize, usize)) -> &T {
        self.at(row, col)
    }
}

impl<const ROWS: usize, const COLS: usize, T> IndexMut<(usize, usize)> for Matrix<ROWS, COLS, T> {
    /// Panics if `(row, col)` is out of range. Use [`Self::get_mut`] when the index may be invalid.
    #[inline]
    #[track_caller]
    fn index_mut(&mut self, (row, col): (usize, usize)) -> &mut T {
        self.at_mut(row, col)
    }
}

impl<const ROWS: usize, const COLS: usize, T: Numeric> Add for Matrix<ROWS, COLS, T> {
    type Output = Self;

    #[inline]
    fn add(mut self, rhs: Self) -> Self {
        self += rhs;
        self
    }
}

impl<const ROWS: usize, const COLS: usize, T: Numeric> AddAssign for Matrix<ROWS, COLS, T> {
    #[inline]
    fn add_assign(&mut self, rhs: Self) {
        for (row, rhs_row) in self.data.iter_mut().zip(&rhs.data) {
            for (a, &b) in row.iter_mut().zip(rhs_row) {
                *a += b;
            }
        }
    }
}

impl<const ROWS: usize, const COLS: usize, T: Numeric> Sub for Matrix<ROWS, COLS, T> {
    type Output = Self;

    #[inline]
    fn sub(mut self, rhs: Self) -> Self {
        self -= rhs;
        self
    }
}

impl<const ROWS: usize, const COLS: usize, T: Numeric> SubAssign for Matrix<ROWS, COLS, T> {
    #[inline]
    fn sub_assign(&mut self, rhs: Self) {
        for (row, rhs_row) in self.data.iter_mut().zip(&rhs.data) {
            for (a, &b) in row.iter_mut().zip(rhs_row) {
                *a -= b;
            }
        }
    }
}

impl<const ROWS: usize, const COLS: usize, T: Numeric> Neg for Matrix<ROWS, COLS, T> {
    type Output = Self;

    #[inline]
    fn neg(mut self) -> Self {
        for row in &mut self.data {
            for x in row.iter_mut() {
                *x = -*x;
            }
        }
        self
    }
}

impl<const ROWS: usize, const COLS: usize, T: Numeric> Mul<T> for Matrix<ROWS, COLS, T> {
    type Output = Self;

    #[inline]
    fn mul(self, scalar: T) -> Self {
        self.scale(scalar)
    }
}

impl<const ROWS: usize, const COLS: usize, const C2: usize, T: Numeric> Mul<Matrix<COLS, C2, T>>
    for Matrix<ROWS, COLS, T>
{
    type Output = Matrix<ROWS, C2, T>;

    #[inline]
    fn mul(self, rhs: Matrix<COLS, C2, T>) -> Matrix<ROWS, C2, T> {
        Matrix::from_fn(|r, c| {
            let mut acc = T::ZERO;
            for k in 0..COLS {
                acc += self[(r, k)] * rhs[(k, c)];
            }
            acc
        })
    }
}

impl<const ROWS: usize, const COLS: usize, T: Numeric> Mul<Vector<COLS, T>>
    for Matrix<ROWS, COLS, T>
{
    type Output = Vector<ROWS, T>;

    #[inline]
    fn mul(self, rhs: Vector<COLS, T>) -> Vector<ROWS, T> {
        Vector::from_fn(|r| {
            let mut acc = T::ZERO;
            for c in 0..COLS {
                acc += self[(r, c)] * rhs[c];
            }
            acc
        })
    }
}

// The 2×2, 3×3, and 4×4 determinant and inverse are written out in closed form. These are the
// sizes seen most often, and the inline expressions keep them low-latency, sparing them the
// loops and pivoting a general factorization would need.
impl<T: Numeric> Matrix<2, 2, T> {}

impl<T: Numeric> Matrix<3, 3, T> {}

// The 4×4 closed form shares the twelve 2×2 row-pair minors between the determinant and the
// adjugate, so a full inverse costs little more than the determinant alone.
impl<T: Numeric> Matrix<4, 4, T> {}