HDF5 / NetCDF4 in GNU Octave
Open data file formats such as HDF5 and NetCDF4 are excellent way to share and store archival data across computing platforms and software languages. Numerical software such as Matlab, GNU Octave, Python, and many more support these data file formats.
The syntax in the code examples below is exactly the same for Matlab and GNU Octave.
Omit the pkg load
and pkg install
statements in Matlab.
HDF5
HDF5 files in GNU Octave are accessed via hdf5oct in similar fashion to Matlab.
From Octave prompt, install the package:
pkg install -forge hdf5oct
Octave program that writes an array to an HDF5 file “example.h5” dataset “/m”:
pkg load hdf5oct
fn = 'example.h5';
h5create (fn, '/m', [3 3]);
h5write (fn, '/m', magic (3));
Observe the file “example.h5” has been created. If the HDF5 command line tools are installed, the contents can be printed from system Terminal:
h5ls -v example.h5
In Octave or Matlab, the HDF5 file can be read to an array:
x = h5read (fn, '/m')
8 1 6
3 5 7
4 9 2
NetCDF4
NetCDF4 files in GNU Octave are accessed via Octave NetCDF4 package. Install the package from Octave prompt:
pkg install -forge netcdf
Write an array to a NetCDF4 file “example.nc” dataset “m”:
pkg load netcdf
fn = 'example.nc';
nccreate (fn, 'm', "Dimensions", {"x", 3, "y", 3});
% must include dimensions or a scalar dataset will be created
ncwrite (fn, 'm', magic (3));
Read the NetCDF4 file “example.nc” to an array:
x = ncread (fn, 'm')
Reference:
- oct-hdf5 package: Octave low-level access to HDF5 files.