diff --git a/src/DataStructures/DynamicMatrix.hpp b/src/DataStructures/DynamicMatrix.hpp index aefe31a90607..cde8ca752b6b 100644 --- a/src/DataStructures/DynamicMatrix.hpp +++ b/src/DataStructures/DynamicMatrix.hpp @@ -75,3 +75,20 @@ struct Options::create_from_yaml> { return result; } }; + +/// Write a `blaze::DynamicMatrix` to a CSV file. +template +std::ostream& write_csv( + std::ostream& os, const blaze::DynamicMatrix& matrix, + const std::string& delimiter = ",") { + for (size_t i = 0; i < matrix.rows(); ++i) { + for (size_t j = 0; j < matrix.columns(); ++j) { + os << matrix(i, j); + if (j + 1 != matrix.columns()) { + os << delimiter; + } + } + os << '\n'; + } + return os; +} diff --git a/tests/Unit/DataStructures/Test_BlazeInteroperability.cpp b/tests/Unit/DataStructures/Test_BlazeInteroperability.cpp index 34eb08b17f1e..870010a426c1 100644 --- a/tests/Unit/DataStructures/Test_BlazeInteroperability.cpp +++ b/tests/Unit/DataStructures/Test_BlazeInteroperability.cpp @@ -100,6 +100,12 @@ SPECTRE_TEST_CASE("Unit.DataStructures.BlazeInteroperability", "[[0., 1., 2.], [3., 0., 4.]]") == blaze::DynamicMatrix{{0., 1., 2.}, {3., 0., 4.}}); + // Test `write_csv` + std::stringstream ss{}; + blaze::DynamicMatrix matrix{{0., 1., 2.}, + {3., 0., 4.}}; + write_csv(ss, matrix); + CHECK(ss.str() == "0,1,2\n3,0,4\n"); } { INFO("CompressedMatrix");