From 7af7eef4593bc889c9be9185bfdef26a03ee50f4 Mon Sep 17 00:00:00 2001
From: Stephane Del Pino <stephane.delpino44@gmail.com>
Date: Mon, 23 Aug 2021 13:47:27 +0200
Subject: [PATCH] Add transpose function to TinyMatrix

---
 src/algebra/TinyMatrix.hpp | 12 ++++++++++++
 tests/test_TinyMatrix.cpp  | 12 ++++++++++++
 2 files changed, 24 insertions(+)

diff --git a/src/algebra/TinyMatrix.hpp b/src/algebra/TinyMatrix.hpp
index 73c187772..0d3b9c0e5 100644
--- a/src/algebra/TinyMatrix.hpp
+++ b/src/algebra/TinyMatrix.hpp
@@ -41,6 +41,18 @@ class [[nodiscard]] TinyMatrix
     return M == N;
   }
 
+  PUGS_INLINE
+  constexpr friend TinyMatrix<N, M, T> transpose(const TinyMatrix& A)
+  {
+    TinyMatrix<N, M, T> tA;
+    for (size_t i = 0; i < M; ++i) {
+      for (size_t j = 0; j < N; ++j) {
+        tA(j, i) = A(i, j);
+      }
+    }
+    return tA;
+  }
+
   PUGS_INLINE
   constexpr size_t dimension() const
   {
diff --git a/tests/test_TinyMatrix.cpp b/tests/test_TinyMatrix.cpp
index 800f8497e..c9b72d5de 100644
--- a/tests/test_TinyMatrix.cpp
+++ b/tests/test_TinyMatrix.cpp
@@ -248,6 +248,18 @@ TEST_CASE("TinyMatrix", "[algebra]")
     REQUIRE_FALSE(TinyMatrix<3, 4>{}.isSquare());
   }
 
+  SECTION("transpose")
+  {
+    TinyMatrix tA = transpose(A);
+
+    REQUIRE(((tA(0, 0) == 1) and (tA(1, 0) == 2) and (tA(2, 0) == 3) and (tA(3, 0) == 4) and   //
+             (tA(0, 1) == 5) and (tA(1, 1) == 6) and (tA(2, 1) == 7) and (tA(3, 1) == 8) and   //
+             (tA(0, 2) == 9) and (tA(1, 2) == 10) and (tA(2, 2) == 11) and (tA(3, 2) == 12)));
+
+    TinyMatrix ttA = transpose(tA);
+    REQUIRE(ttA == A);
+  }
+
   SECTION("checking for matrices output")
   {
     REQUIRE(Catch::Detail::stringify(A) == "[(1,2,3,4)(5,6,7,8)(9,10,11,12)]");
-- 
GitLab