How to write Eigen3::MatrixXd to HDF5 using C++

This example writes a 2D Eigen matrix to an HDF5 file using the C++ API. The code uses the Eigen::MatrixXd type, but you can easily adapt it to other Eigen types.

#include <H5Cpp.h>

void writeToHDF5(const Eigen::MatrixXd& matrix, const std::string& mat_file_path) {
    try {
        // Create a new file using the default property lists.
        H5::H5File file(mat_file_path, H5F_ACC_TRUNC);

        // Create the data space for the dataset.
        hsize_t dims[2] = {matrix.rows(), matrix.cols()};
        H5::DataSpace dataspace(2, dims);

        // Create the dataset.
        H5::DataSet dataset = file.createDataSet("matrix", H5::PredType::NATIVE_DOUBLE, dataspace);

        // Write the data to the dataset.
        dataset.write(matrix.data(), H5::PredType::NATIVE_DOUBLE);
    } catch (H5::FileIException& error) {
        error.printErrorStack();
    } catch (H5::DataSetIException& error) {
        error.printErrorStack();
    } catch (H5::DataSpaceIException& error) {
        error.printErrorStack();
    }
}

Compile command example:

g++ -o test test.cpp -I/usr/include/eigen3/-I/usr/include/hdf5/serial -L/usr/lib/x86_64-linux-gnu/hdf5/serial/ -lhdf5_cpp -lhdf5