如何使用 C++ 将 Eigen3::MatrixXd 写入 HDF5

此示例使用 C++ API 将 2D Eigen 矩阵写入 HDF5 文件。代码使用 Eigen::MatrixXd 类型,但你可以轻松地将其适配到其他 Eigen 类型。

write_matrix_hdf5.cpp
#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();
    }
}

编译命令示例:

build_write_matrix_hdf5.sh
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

Check out similar posts by category: C/C++