Skip to content

Commit ef08d4d

Browse files
feat(math): diagonal matrices and diagonal products (#383)
* feat(math): diagonal matrices and diagonal products Diagonal(d) and DiagonalOf(M) convert between a vector and a diagonal matrix. ScaleColumns(M, d) and DiagonalCongruence(d, M) compute M diag(d) and diag(d) M diag(d) entry by entry, so applying per-joint gains, sign conventions or unit scalings to a Jacobian or a mass matrix costs one or two multiplications per entry instead of full matrix products. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_014WUWh8Fw5EhcfvNuXz3jjU * docs(math): list the diagonal helpers in the math index Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_014WUWh8Fw5EhcfvNuXz3jjU --------- Co-authored-by: Claude <noreply@anthropic.com>
1 parent c7bff11 commit ef08d4d

4 files changed

Lines changed: 101 additions & 6 deletions

File tree

‎doc/math/MatrixOperations.md‎

Lines changed: 19 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,10 @@ Small structural matrix utilities that are needed across the library but do not
77
- **`Symmetrize`** enforces exact symmetry on a matrix that should be symmetric in theory but drifts under floating-point round-off.
88
- **`CongruenceTransform`** computes the quadratic form `A·M·Aᵀ` — the single most common shape in covariance-propagating code (Kalman predict `F·P·Fᵀ`, innovation covariance `H·P·Hᵀ`, Joseph update `(I−KH)·P·(I−KH)ᵀ`, etc.).
99

10-
Both are recurring needs in Kalman filters, EM parameter updates, and Riccati/Lyapunov solvers.
10+
- **`Diagonal`** and **`DiagonalOf`** convert between a vector and a diagonal matrix.
11+
- **`ScaleColumns`** and **`DiagonalCongruence`** compute `M·diag(d)` and `diag(d)·M·diag(d)` without forming the diagonal matrix: per-joint gains, sign conventions and unit scalings applied to Jacobians and mass matrices.
12+
13+
The first two are recurring needs in Kalman filters, EM parameter updates, and Riccati/Lyapunov solvers; the diagonal products recur wherever a matrix is expressed in rescaled coordinates.
1114

1215
## Mathematical Theory
1316

@@ -19,19 +22,30 @@ $$M = \underbrace{\tfrac{1}{2}(M + M^\top)}_{\text{symmetric}} + \underbrace{\tf
1922

2023
If $M$ is symmetric, `CongruenceTransform` returns a symmetric result exactly (in exact arithmetic): $(AMA^\top)^\top = A M^\top A^\top = A M A^\top$. This makes it the natural building block for propagating a covariance $P$ through a linear map $A$: $P \mapsto A P A^\top$.
2124

25+
With $D = \operatorname{diag}(d)$, a product with a diagonal matrix scales columns, or rows and columns, entry by entry:
26+
27+
$$(M D)_{ij} = M_{ij}\, d_j, \qquad (D M D)_{ij} = d_i\, M_{ij}\, d_j$$
28+
29+
so neither product needs a matrix multiplication. $D M D$ is a congruence: it keeps a symmetric $M$ symmetric, and a positive-definite $M$ positive definite when every $d_i \neq 0$.
30+
2231
## Complexity Analysis
2332

24-
| Operation | Time | Space | Notes |
25-
|---------------------|--------------------|----------|---------------------------------------------------------|
26-
| Symmetrize | $O(n^2)$ | $O(n^2)$ | One transpose, add, scale |
27-
| CongruenceTransform | $O(n^2 m + n m^2)$ | $O(nm)$ | For $A \in \mathbb{R}^{n\times m}$, two matrix products |
33+
| Operation | Time | Space | Notes |
34+
|----------------------|--------------------|----------|-------------------------------------------------------------------------|
35+
| Symmetrize | $O(n^2)$ | $O(n^2)$ | One transpose, add, scale |
36+
| CongruenceTransform | $O(n^2 m + n m^2)$ | $O(nm)$ | For $A \in \mathbb{R}^{n\times m}$, two matrix products |
37+
| Diagonal, DiagonalOf | $O(n)$ | $O(n^2)$ | Copies the diagonal only |
38+
| ScaleColumns | $O(nm)$ | $O(nm)$ | One multiplication per entry |
39+
| DiagonalCongruence | $O(n^2)$ | $O(n^2)$ | Two multiplications per entry, against $O(n^3)$ for two matrix products |
2840

2941
## Step-by-Step Walkthrough
3042

3143
**Symmetrize** — for $M = \begin{bmatrix}1 & 3 \\ -1 & 2\end{bmatrix}$: $M^\top = \begin{bmatrix}1 & -1 \\ 3 & 2\end{bmatrix}$, so $\tfrac{1}{2}(M + M^\top) = \begin{bmatrix}1 & 1 \\ 1 & 2\end{bmatrix}$ — off-diagonals averaged, diagonal unchanged.
3244

3345
**CongruenceTransform** — with $A \in \mathbb{R}^{n\times m}$ and symmetric $M \in \mathbb{R}^{m\times m}$, the result $A M A^\top \in \mathbb{R}^{n\times n}$ is the covariance of $A x$ when $x$ has covariance $M$.
3446

47+
**DiagonalCongruence** — for $d = (2, -3)$ and $M = \begin{bmatrix}1 & 3 \\ -1 & 2\end{bmatrix}$: $(DMD)_{01} = 2 \cdot 3 \cdot (-3) = -18$, $(DMD)_{10} = -3 \cdot (-1) \cdot 2 = 6$ and $(DMD)_{11} = 9 \cdot 2 = 18$, as $\operatorname{diag}(d)\,M\,\operatorname{diag}(d)$ gives with two full products.
48+
3549
## Pitfalls & Edge Cases
3650

3751
**Symmetrize is not a fix for indefiniteness** — it removes the skew part but does not make a matrix positive-definite; covariance code typically also adds a small diagonal jitter (`+ εI`) separately.

‎doc/math/README.md‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -14,7 +14,7 @@ Core mathematical primitives for numerical computation.
1414
| [Givens Rotation](GivensRotation.md) | Plane rotation zeroing one entry — streaming/sparse factorization primitive |
1515
| [Triangular Solve](TriangularSolve.md) | Lower/upper-triangular forward and back-substitution shared by Gaussian elimination, Cholesky, and QR |
1616
| [Cholesky Decomposition](CholeskyDecomposition.md) | SPD factorization $A=LL^T$ with `Factor` (L) and `Solve` (SPD system) — twice as fast as LU |
17-
| [Matrix Operations](MatrixOperations.md) | Structural matrix utilities — `Symmetrize` (closest symmetric matrix) |
17+
| [Matrix Operations](MatrixOperations.md) | Structural matrix utilities — `Symmetrize`, `CongruenceTransform`, diagonal matrices and entry-wise diagonal products |
1818
| [Step Response Metrics](StepResponseMetrics.md) | Rise time, settling time, percent overshoot, peak time, and steady-state error from a bounded step-response vector |
1919
| [Matrix Exponential](MatrixExponential.md) | Scaling-and-squaring with diagonal (6,6) Padé approximant — exact ODE solution operator and discretisation engine |
2020
| [Consistency Metrics](ConsistencyMetrics.md) | NEES/NIS estimator consistency with χ² gates — normalised estimation error squared and normalised innovation squared |

‎numerical/math/MatrixOperations.hpp‎

Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -20,4 +20,46 @@ namespace math
2020
static_assert(std::is_floating_point_v<T>, "CongruenceTransform supports floating-point types");
2121
return a * m * a.Transpose();
2222
}
23+
24+
template<typename T, std::size_t N>
25+
[[nodiscard]] SquareMatrix<T, N> Diagonal(const Vector<T, N>& d)
26+
{
27+
static_assert(std::is_floating_point_v<T>, "Diagonal supports floating-point types");
28+
SquareMatrix<T, N> result{};
29+
for (std::size_t i = 0; i < N; ++i)
30+
result.at(i, i) = d.at(i, 0);
31+
return result;
32+
}
33+
34+
template<typename T, std::size_t N>
35+
[[nodiscard]] Vector<T, N> DiagonalOf(const SquareMatrix<T, N>& m)
36+
{
37+
static_assert(std::is_floating_point_v<T>, "DiagonalOf supports floating-point types");
38+
Vector<T, N> result{};
39+
for (std::size_t i = 0; i < N; ++i)
40+
result.at(i, 0) = m.at(i, i);
41+
return result;
42+
}
43+
44+
template<typename T, std::size_t Rows, std::size_t Cols>
45+
[[nodiscard]] OPTIMIZE_FOR_SPEED Matrix<T, Rows, Cols> ScaleColumns(const Matrix<T, Rows, Cols>& m, const Vector<T, Cols>& d)
46+
{
47+
static_assert(std::is_floating_point_v<T>, "ScaleColumns supports floating-point types");
48+
Matrix<T, Rows, Cols> result{ m };
49+
for (std::size_t i = 0; i < Rows; ++i)
50+
for (std::size_t j = 0; j < Cols; ++j)
51+
result.at(i, j) *= d.at(j, 0);
52+
return result;
53+
}
54+
55+
template<typename T, std::size_t N>
56+
[[nodiscard]] OPTIMIZE_FOR_SPEED SquareMatrix<T, N> DiagonalCongruence(const Vector<T, N>& d, const SquareMatrix<T, N>& m)
57+
{
58+
static_assert(std::is_floating_point_v<T>, "DiagonalCongruence supports floating-point types");
59+
SquareMatrix<T, N> result{ m };
60+
for (std::size_t i = 0; i < N; ++i)
61+
for (std::size_t j = 0; j < N; ++j)
62+
result.at(i, j) *= d.at(i, 0) * d.at(j, 0);
63+
return result;
64+
}
2365
}

‎numerical/math/test/TestMatrixOperations.cpp‎

Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -161,3 +161,42 @@ TEST_F(MatrixOperationsTest, CongruenceTransformZeroMYieldsZeroResult)
161161
for (std::size_t j = 0; j < 2; ++j)
162162
EXPECT_NEAR(result.at(i, j), 0.0f, math::Tolerance<float>());
163163
}
164+
165+
TEST_F(MatrixOperationsTest, DiagonalPlacesTheVectorOnTheDiagonalAndDiagonalOfReadsItBack)
166+
{
167+
const math::Vector<float, 2> d{ 2.0f, -3.0f };
168+
169+
const auto matrix = math::Diagonal(d);
170+
const auto back = math::DiagonalOf(matrix);
171+
172+
EXPECT_NEAR(matrix.at(0, 0), 2.0f, math::Tolerance<float>());
173+
EXPECT_NEAR(matrix.at(1, 1), -3.0f, math::Tolerance<float>());
174+
EXPECT_NEAR(matrix.at(0, 1), 0.0f, math::Tolerance<float>());
175+
EXPECT_NEAR(matrix.at(1, 0), 0.0f, math::Tolerance<float>());
176+
EXPECT_NEAR(back.at(0, 0), 2.0f, math::Tolerance<float>());
177+
EXPECT_NEAR(back.at(1, 0), -3.0f, math::Tolerance<float>());
178+
}
179+
180+
TEST_F(MatrixOperationsTest, ScaleColumnsMatchesTheProductWithADiagonalOnTheRight)
181+
{
182+
const math::Vector<float, 2> d{ 2.0f, -3.0f };
183+
184+
const auto result = math::ScaleColumns(asymmetric, d);
185+
const auto expected = asymmetric * math::Diagonal(d);
186+
187+
for (std::size_t i = 0; i < 2; ++i)
188+
for (std::size_t j = 0; j < 2; ++j)
189+
EXPECT_NEAR(result.at(i, j), expected.at(i, j), math::Tolerance<float>());
190+
}
191+
192+
TEST_F(MatrixOperationsTest, DiagonalCongruenceMatchesTheProductWithADiagonalOnBothSides)
193+
{
194+
const math::Vector<float, 2> d{ 2.0f, -3.0f };
195+
196+
const auto result = math::DiagonalCongruence(d, asymmetric);
197+
const auto expected = math::Diagonal(d) * asymmetric * math::Diagonal(d);
198+
199+
for (std::size_t i = 0; i < 2; ++i)
200+
for (std::size_t j = 0; j < 2; ++j)
201+
EXPECT_NEAR(result.at(i, j), expected.at(i, j), math::Tolerance<float>());
202+
}

0 commit comments

Comments
 (0)