This example shows how to use the h5 array interface to write/read a 2-dimensional array to/from HDF5.
We first write a 2-dimensional 5x5
array to an HDF5 file.
Then we use an h5::array_interface::hyperslab to select every other column from the original 5x5
matrix and read it into a 5x3
h5::array_interface::array_view.
Finally, we output the result to stdout.
#include <iostream>
#include <numeric>
#include <vector>
#include <H5Tpublic.h>
int main() {
std::vector<int> data (25, 0);
std::iota(data.begin(), data.end(), 0);
int rank = 2;
int rows_w = 5;
int cols_w = 5;
view.slab.count[0] = rows_w;
view.slab.count[1] = cols_w;
view.parent_shape[0] = rows_w;
view.parent_shape[1] = cols_w;
std::vector<int> read_data(15, 0);
int rows_r = 5;
int cols_r = 3;
read_view.slab.count[0] = rows_r;
read_view.slab.count[1] = cols_r;
read_view.parent_shape[0] = rows_r;
read_view.parent_shape[1] = cols_r;
read_slab.count[0] = rows_r;
read_slab.count[1] = cols_r;
read_slab.stride[0] = 1;
read_slab.stride[1] = 2;
for (int i = 0; i < rows_r; ++i) {
for (int j = 0; j < cols_r; ++j) {
std::cout << read_data[i * cols_r + j] << " ";
}
std::cout << std::endl;
}
}
A handle to an HDF5 file.
datatype hdf5_type()
Map a given C++ type to an HDF5 datatype.
void read(group g, std::string const &name, array_view v, hyperslab sl)
Read a given hyperslab from an HDF5 dataset into an array view.
dataset_info get_dataset_info(dataset ds)
Retrieve the shape and the h5::datatype from a dataset.
void write(group g, std::string const &name, array_view const &v, bool compress)
Write an array view to an HDF5 dataset.
Includes all relevant h5 headers.
Struct representing a view on an n-dimensional array/dataspace.
Struct representing an HDF5 hyperslab.
Output:
0 2 4
5 7 9
10 12 14
15 17 19
20 22 24
Contents of view.h5
:
HDF5 "view.h5" {
GROUP "/" {
DATASET "view" {
DATATYPE H5T_STD_I32LE
DATASPACE SIMPLE { ( 5, 5 ) / ( 5, 5 ) }
DATA {
(0,0): 0, 1, 2, 3, 4,
(1,0): 5, 6, 7, 8, 9,
(2,0): 10, 11, 12, 13, 14,
(3,0): 15, 16, 17, 18, 19,
(4,0): 20, 21, 22, 23, 24
}
}
}
}