| MATLAB® | ![]() |
| On this page… |
|---|
Note For information about working with HDF4 data, which is a completely separate, incompatible format, see Hierarchical Data Format (HDF4) Files. |
Hierarchical Data Format, Version 5, (HDF5) is a general-purpose, machine-independent standard for storing scientific data in files, developed by the National Center for Supercomputing Applications (NCSA). HDF5 is used by a wide range of engineering and scientific fields that want a standard way to store data so that it can be shared. For more information about the HDF5 file format, read the HDF5 documentation available at the HDF Web site (http://www.hdfgroup.org).
The MATLAB high-level HDF5 functions provide an easy way to import data or metadata from an HDF5 file, or write data to an HDF5 file. The following sections provide more detail about using these functions.
HDF5 files can contain data and metadata, called attributes. HDF5 files organize the data and metadata in a hierarchical structure similar to the hierarchical structure of a UNIX file system.
In an HDF5 file, the directories in the hierarchy are called groups. A group can contain other groups, data sets, attributes, links, and data types. A data set is a collection of data, such as a multidimensional numeric array or string. An attribute is any data that is associated with another entity, such as a data set. A link is similar to a UNIX file system symbolic link. Links are a way to reference data without having to make a copy of the data.
Data types are a description of the data in the data set or attribute. Data types tell how to interpret the data in the data set. For example, a file might contain a data type called "Reading" that is comprised of three elements: a longitude value, a latitude value, and a temperature value.
To explore the hierarchical organization of an HDF5 file, use the hdf5info function. For example, to find out what the sample HDF5 file, example.h5, contains, use this syntax:
fileinfo = hdf5info('example.h5');hdf5info returns a structure that contains various information about the HDF5 file, including the name of the file and the version of the HDF5 library that MATLAB is using:
fileinfo =
Filename: 'example.h5'
LibVersion: '1.6.5'
Offset: 0
FileSize: 8172
GroupHierarchy: [1x1 struct]In the information returned by hdf5info, look at the GroupHierarchy field. This field is a structure that describes the top-level group in the file, called the root group. Using the UNIX convention, HDF5 names this top-level group / (forward slash), as shown in the Name field of the GroupHierarchy structure.
toplevel = fileinfo.GroupHierarchy
toplevel =
Filename: 'C:\matlab\toolbox\matlab\demos\example.h5'
Name: '/'
Groups: [1x2 struct]
Datasets: []
Datatypes: []
Links: []
Attributes: [1x2 struct]By looking at the Groups and Attributes fields, you can see that the file contains two groups and two attributes. The Datasets, Datatypes, and Links fields are all empty, indicating that the root group does not contain any data sets, data types, or links.
The following figure illustrates the organization of the root group in the sample HDF5 file example.h5.
Organization of the Root Group of the Sample HDF5 File

To explore the contents of the sample HDF5 file further, examine one of the two structures in the Groups field of the GroupHierarchy structure. Each structure in this field represents a group contained in the root group. The following example shows the contents of the second structure in this field.
level2 = toplevel.Groups(2)
level2 =
Filename: 'C:\matlab\toolbox\matlab\demos\example.h5'
Name: '/g2'
Groups: []
Datasets: [1x2 struct]
Datatypes: []
Links: []
Attributes: []In the sample file, the group named /g2 contains two data sets. The following figure illustrates this part of the sample HDF5 file organization.
Organization of the Data Set /g2 in the Sample HDF5 File

To get information about a data set, look at either of the structures returned in the Datasets field. These structures provide information about the data set, such as its name, dimensions, and data type.
dataset1 = level2.Datasets(1)
dataset1 =
Filename: 'L:\matlab\toolbox\matlab\demos\example.h5'
Name: '/g2/dset2.1'
Rank: 1
Datatype: [1x1 struct]
Dims: 10
MaxDims: 10
Layout: 'contiguous'
Attributes: []
Links: []
Chunksize: []
Fillvalue: []By examining the structures at each level of the hierarchy, you can traverse the entire file. The following figure describes the complete hierarchical organization of the sample file example.h5.
Hierarchical Structure of example.h5 HDF5 File

To read data or metadata from an HDF5 file, use the hdf5read function. As arguments, you must specify the name of the HDF5 file and the name of the data set or attribute. Alternatively, you can specify just the field in the structure returned by hdf5info that contains the name of the data set or attribute; hdf5read can determine the file name from the Filename field in the structure. For more information about finding the name of a data set or attribute in an HDF5 file, see Determining the Contents of an HDF5 File.
To illustrate, this example reads the data set, /g2/dset2.1 from the HDF5 sample file example.h5.
data = hdf5read('example.h5','/g2/dset2.1');
The return value contains the values in the data set, in this case a 1-by-10 vector of single-precision values:
data =
1.0000
1.1000
1.2000
1.3000
1.4000
1.5000
1.6000
1.7000
1.8000
1.9000The hdf5read function maps HDF5 data types to appropriate MATLAB data types, whenever possible. If the HDF5 file contains data types that cannot be represented in MATLAB, hdf5write uses one of the predefined MATLAB HDF5 data type objects to represent the data.
For example, if an HDF5 data set contains four array elements, hdf5read can return the data as a 1-by-4 array of hdf5.h5array objects:
whos Name Size Bytes Class data 1x4 hdf5.h5array Grand total is 4 elements using 0 bytes
For more information about the MATLAB HDF5 data type objects, see Mapping HDF5 Data Types to MATLAB Data Types.
To write data or metadata from the MATLAB workspace to an HDF5 file, use the hdf5write function. As arguments, specify:
Name of an existing HDF5 file, or the name you want to assign to a new file.
Name of an existing data set or attribute, or the name you want to assign to a new data set or attribute. To learn how to determine the name of data sets in an existing HDF5 file, see Determining the Contents of an HDF5 File.
Data or metadata you want to write to the file. hdf5write converts MATLAB data types to the appropriate HDF5 data type automatically. For nonatomic data types, you can also create HDF5 objects to represent the data.
This example creates a 5-by-5 array of uint8 values and then writes the array to an HDF5 file. By default, hdf5write overwrites the file, if it already exists. The example specifies an hdf5write mode option to append data to existing file.
Create a MATLAB variable in the workspace. This example creates a 5-by-5 array of uint8 values.
testdata = uint8(magic(5))
Write the data to an HDF5 file. As arguments to hdf5read, the example specifies the name you want to assign to the HDF5 file, the name you want to assign to the data set, and the MATLAB variable.
hdf5write('myfile.h5', '/dataset1', testdata)To add data to an existing file, you must use the 'writemode' option, specifying the'append' value. The file must already exist and it cannot already contain a data set with the same name
hdf5write('myfile.h5', '/dataset12', testdata,'writemode','append')If you are writing simple data sets, such as scalars, strings, or a simple compound data types, you can just pass the data directly to hdf5write; this function automatically maps the MATLAB data types to appropriate HDF5 data types. However, if your data is a complex data set, you might need to use one of the predefined MATLAB HDF5 objects to pass the data to the hdf5write function. The HDF5 objects are designed for situations where the mapping between MATLAB and HDF5 types is ambiguous.
For example, when passed a cell array of strings, the hdf5write function writes a data set made up of strings, not a data set of arrays containing strings. If that is not the mapping you intend, use HDF5 objects to specify the correct mapping. In addition, note that HDF5 makes a distinction between the size of a data set and the size of a data type. In MATLAB, data types are always scalar. In HDF5, data types can have a size; that is, types can be either scalar (like MATLAB) or m-by-n. In HDF5, a 5-by-5 data set containing a single uint8 value in each element is distinct from a 1-by-1 data set containing a 5-by-5 array of uint8 values. In the first case, the data set contains 25 observations of a single value; in the second case, the data set contains a single observation with 25 values. For more information about the MATLAB HDF5 data type objects, see Mapping HDF5 Data Types to MATLAB Data Types.
When the hdf5read function reads data from an HDF5 file into the MATLAB workspace, it maps HDF5 data types to MATLAB data types, depending on whether the data in the data set is in an atomic data type or a nonatomic composite data type.
Mapping Atomic Data Types. Atomic data types describe commonly used binary formats for numbers (integers and floating point) and characters (ASCII). Because different computing architectures and programming languages support different number and character representations, the HDF5 library provides the platform-independent data types, which it then maps to an appropriate data type for each platform. For example, a computer may support 8-, 16-, 32-, and 64-bit signed integers, stored in memory in little endian byte order.
If the data in the data set is stored in one of the HDF5 atomic data types, hdf5read uses the equivalent MATLAB data type to represent the data. Each data set contains a Datatype field that names the data type. For example, the data set /g2/dset2.2 in the sample HDF5 file includes atomic data and data type information.
dtype = dataset1.Datatype
dtype =
Name: []
Class: 'H5T_IEEE_F32BE'
Elements: []The H5T_IEEE_F32BE class name indicates the data is a 4-byte, big endian, IEEE floating-point data type. (See the HDF5 specification for more information about atomic data types.)
Mapping Composite Data Types. A composite data type is an aggregation of one or more atomic data types. Composite data types include structures, multidimensional arrays, and variable-length data types (one-dimensional arrays).
If the data in the data set is stored in one of the HDF5 nonatomic data types and the data cannot be represented in the workspace using a native MATLAB data type,hdf5read uses one of a set of classes MATLAB defines to represent HDF5 data types. The following figure illustrates the hdf5 class and its subclasses. For more information about a specific class, see the sections that follow. To learn more about the HDF5 data types in general, see the HDF Web page at http://www.hdfgroup.org.

For example, if an HDF5 file contains a data set made up of an enumerated data type which cannot be represented in MATLAB, hdf5read uses the HDF5 h5enum class to represent the data. An h5enum object has data members that store the enumerations (text strings), their corresponding values, and the enumerated data.
You might also need to use these HDF5 data type classes when using the hdf5write function to write data from the MATLAB workspace to an HDF5 file. By default, hdf5write can convert most MATLAB data to appropriate HDF5 data types. However, if this default data type mapping is not suitable, you can create HDF5 data types directly.
To access the data in the data set in the MATLAB workspace, you must access the Data field in the object.
This example converts a simple MATLAB vector into an h5array object and then displays the fields in the object:
vec = [ 1 2 3];
hhh = hdf5.h5array(vec);
hhh:
Name: ''
Data: [1 2 3]
hhh.Data
ans =
1 2 3MATLAB HDF5 h5array Data Class. The h5array data class associates a name with an array. The following tables list the class data members and methods.
| Data Members | Description |
|---|---|
| Data | Multidimensional array |
| Name | Text string specifying name of the object |
| Methods | Description |
|---|---|
| arr = hdf5.h5array | Creates an h5array object. |
| arr = hdf5.h5array(data) | Creates an h5array object, where data specifies the value of the Data member. data can be numeric, a cell array, or an HDF5 data type. |
| setData(arr, data) | Sets the value of the Data member, where arr is an h5array object and data can be numeric, a cell array, or an HDF5 data type. |
| setName(arr, name) | Sets the value of the Name member, where arr is an h5array object and name is a string or cell array. |
MATLAB HDF5 h5compound Data Class. The h5compound data class associates a name with a structure. You can define the field names in the structure and their values. The following tables list the class data members and methods.
| Data Members | Description |
|---|---|
| Data | Multidimensional array |
| Name | Text string specifying name of the object |
| MemberNames | Text strings specifying name of the object |
| Methods | Description |
|---|---|
| C = hdf5.h5compound | Creates an h5compound object. |
| C = hdf5.h5compound(n1,n2,...) | Creates an h5compound object, where n1, n2 and so on are text strings that specify field names. The constructor creates a corresponding data field for every member name. |
| addMember(C, mName) | Creates a new field in the object C. mName specifies the name of the field. |
| setMember(C, mName, mData) | Sets the value of the Data element associated with the field specified by mName, where C is an h5compound object and mData can be numeric or an HDF5 data type. |
| setMemberNames(C, n1, n2,...) | Specifies the names of fields in the structure, where C is an h5compound object and n1,n2, and so on are text strings that specify field names. The method creates a corresponding data field for every name specified. |
| setName(C, name) | Sets the value of the Name member, where C is an h5compound object and name is a string or cell array. |
MATLAB HDF5 h5enum Data Class. The h5enum data class defines an enumerated type. You can specify the enumerations (text strings) and the values they represent. The following tables list the class data members and methods.
| Data Members | Description |
|---|---|
| Data | Multidimensional array |
| Name | Text string specifying name of the object |
| EnumNames | Text string specifying the enumerations, that is, the text strings that represent values |
| EnumValues | Values associated with enumerations |
| Methods | Description |
|---|---|
| E = hdf5.h5enum | Creates an h5enum object. |
| E = hdf5.h5enum(eNames, eVals) | Creates an h5enum object, where eNames is
a cell array of strings, and eVals is vector of
integers. eNames and eVals must
have the same number of elements. |
| defineEnum(E, eNames, eVals) | Defines the set of enumerations with the integer values they represent where eNames is a cell array of strings, and eVals is vector of integers. eNames and eVals must have the same number of elements. |
| enumdata = getString(E) | Returns a cell array containing the names of the enumerations, where E is an h5enum object. |
| setData(E, eData) | Sets the value of the object's Data member,
where E is an h5enum object
and eData is a vector of integers. |
| setEnumNames(E, eNames) | Specifies the enumerations, where E is an h5enum object and eNames is a cell array of strings. |
| setEnumValues(E, eVals) | Specifies the value associated with each enumeration, where E is an h5enum object and eVals is a vector of integers. |
| setName(E, name) | Sets the value of the object's Name member, where E is an h5enum object and name is a string or cell array. |
This example uses an HDF5 enumeration object.
Create an HDF5 enumerated object.
enum_obj = hdf5.h5enum;
Define the enumerated values and their corresponding names.
enum_obj.defineEnum({'RED' 'GREEN' 'BLUE'}, uint8([1 2 3]));
enum_obj now contains the definition of the enumeration that associates the names RED, GREEN, and BLUE with the numbers 1, 2, and 3.
Add enumerated data to the object.
enum_obj.setData(uint8([2 1 3 3 2 3 2 1]));
In the HDF5 file, these numeric values map to the enumerated values GREEN, RED, BLUE, BLUE, GREEN, etc.
Write the enumerated data to a data set named objects in an HDF5 file.
hdf5write('myfile3.h5', '/g1/objects', enum_obj);Read the enumerated data set from the file.
ddd = hdf5read('myfile3.h5','/g1/objects')
hdf5.h5enum:
Name: ''
Data: [2 1 3 3 2 3 2 1]
EnumNames: {'RED' 'GREEN' 'BLUE'}
EnumValues: [1 2 3]MATLAB HDF5 h5string Data Class. The h5string data class associates a name with a text string and provides optional padding behavior. The following tables list the class data members and methods.
| Data Members | Description |
|---|---|
| Data | Multidimensional array |
| Name | Text string specifying name of the object |
| Length | Scalar defining length of string |
| Padding | Type of padding to use: 'spacepad' 'nullterm' 'nullpad' |
| Methods | Description |
|---|---|
| str = hdf5.h5string | Creates an h5string object. |
| str = hdf5.h5string(data) | Creates an h5string object, where data is a text string. |
| str = hdf5.h5string(data, padtype) | Creates an h5stringobject, where data is a text string and padtype specifies the type of padding to use. |
| setData(str, data) | Sets the value of the object's Data member, where str is an h5string object anddata is a text string. |
| setLength(str, lenVal) | Sets the value of the object's Length member,
where str is an h5string object
and lenVal is a scalar. |
| setName(str, name) | Sets the value of the object's Name member, where str is an h5string object and name is a string or cell array. |
| setPadding(str, padType) | Specifies the value of the object's Padding member, where str is an h5string object and padType is a text string specifying one of the supported pad types. |
The following example creates an HDF5 string object.
hdf5.h5vlen({0 [0 1] [0 2] [0:10]})
hdf5.h5vlen:
Name: ''
Data: [0 0 1 0 2 0 1 2 3 4 5 6 7 8 9 10]The following example creates an HDF5 h5vlen object.
hdf5.h5vlen({0 [0 1] [0 2] [0:10]})
hdf5.h5vlen:
Name: ''
Data: [0 0 1 0 2 0 1 2 3 4 5 6 7 8 9 10]MATLAB HDF5 h5vlen Data Class. The h5vlen data class associates a name with an array. The following tables list the class data members and methods.
| Data Members | Description |
|---|---|
| Data | Multidimensional array |
| Name | Text string specifying name of the object |
| Methods | Description |
|---|---|
| V = hdf5.h5vlen | Creates an h5vlen object. |
| V = hdf5.h5vlen(data) | Creates an h5vlen object, where data specifies the value of the Data member. data can be numeric, a cell array, or an HDF5 data type. |
| setData(V, data) | Sets the value of the object's Data member, where V is an h5vlen object and data can be a scalar, vector, text string, a cell array, or an HDF5 data type. |
| setName(V, name) | Sets the value of the object'sName member, where V is an h5vlen object and name is a string or cell array. |
MATLAB provides direct access to the over 200 functions in the HDF5 library by creating MATLAB functions that correspond to the functions in the HDF5 library. In this way, you can access the features of the HDF5 library from MATLAB, such as reading and writing complex data types and using the HDF5 subsetting capabilities.
The HDF5 library organizes the library functions into groups, called interfaces. For example, all the routines related to working with files, such as opening and closing, are in the H5F interface, where F stands for file. MATLAB organizes the low-level HDF5 functions into classes that correspond to each HDF5 interface. For example, the MATLAB functions that correspond to the HDF5 file interface (H5F) are in the @H5F class directory. For a complete list of the HDF5 interfaces and the corresponding MATLAB class directories, see hdf5.
The following sections provide more details about how to use the MATLAB HDF5 low-level functions. Topics covered include:
Note This section does not attempt to describe all features of the HDF5 library or explain basic HDF5 programming concepts. To use the MATLAB HDF5 low-level functions effectively, you must refer to the official HDF5 documentation available at the HDF Web site (http://www.hdfgroup.org). |
In most cases, the syntax of the MATLAB low-level HDF5 functions is identical to the syntax of the corresponding HDF5 library functions. For example, the following is the function signature of the H5Fopen function in the HDF5 library. In the HDF5 function signatures, hid_t and herr_t are HDF5 types that return numeric values that represent object identifiers or error status values.
hid_t H5Fopen(const char *name, unsigned flags, hid_t access_id ) /* C syntax */
In MATLAB, each function in an HDF5 interface is a method of a MATLAB class. To view the function signature for a function, specify the class directory name and then the function name, as in the following.
help @H5F/open
The following shows the signature of the corresponding MATLAB function. First note that, because it's a method of a class, you must use the dot notation to call the MATLAB function: H5F.open. This MATLAB function accepts the same three arguments as the HDF5 function: a text string for the name, an HDF5-defined constant for the flags argument, and an HDF5 property list ID. You use property lists to specify characteristics of many different HDF5 objects. In this case, it's a file access property list. Refer to the HDF5 documentation to see which constants can be used with a particular function and note that, in MATLAB, constants are passed as text strings.
file_id = H5F.open(name, flags, plist_id)
There are, however, some functions where the MATLAB function signature is different than the corresponding HDF5 library function. The following sections describe some general differences that you should keep in mind when using the MATLAB low-level HDF5 functions.
Output Parameters Become Return Values. Some HDF5 library functions use function parameters to return data on the right-hand side (RHS) of the function signature, i.e. as input parameters. The corresponding MATLAB function, because MATLAB allows multiple return values, moves these output parameters to the left-hand side (LHS) of the function signature, i.e. as return values. To illustrate, look at the H5Dread function. This function returns data in the buf parameter.
herr_t H5Dread(hid_t dataset_id, hid_t mem_type_id, hid_t mem_space_id,
hid_t file_space_id, hid_t xfer_plist_id, void * buf ) /* C syntax */The corresponding MATLAB function changes the output parameter buf into a return value. Note that the HDF5 error return is not used. In MATLAB, the nonzero or negative value herr_t return values become MATLAB errors. Use MATLAB try-catch statements to handle errors.
buf = H5D.read(dataset_id, mem_type_id, mem_space_id, file_space_id, plist_id)
String Length Parameters Unnecessary. The length parameter used by some HDF5 library functions to specify the length of string parameters are not necessary in the corresponding MATLAB function. For example, the H5Aget_name function in the HDF5 library includes a buffer as an output parameter and the size of the buffer as an input parameter.
ssize_t H5Aget_name(hid_t attr_id,size_t buf_size,char *buf ) /* C syntax */
The corresponding MATLAB function changes the output parameter buf into a return value and drops the buf_size parameter:
attr_name = H5A.get_name(attr_id)
Use Empty Array to Specify NULL. The MATLAB functions use empty arrays ([]) where HDF5 library functions accept the value NULL. For example, the H5Dfill function in the HDF5 library accepts the value NULL in place of a specified fill value.
herr_t H5Dfill(const void *fill, hid_t fill_type_id, void *buf,
hid_t buf_type_id, hid_t space_id ) /* C syntax */When using the corresponding MATLAB function, you can specify an empty array ([]) instead of NULL.
Specifying Multiple Constants. Some functions in the HDF5 library require you to specify an array of constants. For example, in the H5Screate_simple function, if you want to specify that each dimension in the data space can be unlimited, you use the constant H5S_UNLIMITED for each dimension in maxdims. In MATLAB, because you pass constants as text strings, you must use a cell array to achieve the same result. The following code fragment provides an example of using a cell array to specify this constant for each dimension of this data space.
ds_id = H5S.create_simple(2,[3 4],{'H5S_UNLIMITED' 'H5S_UNLIMITED'});
When the HDF5 low-level functions read data from an HDF5 file or write data to an HDF5 file, the functions map HDF5 data types to MATLAB data types automatically.
For atomic data types, such as commonly used binary formats for numbers (integers and floating point) and characters (ASCII), the mapping is typically straightforward because MATLAB supports similar types. See the table Mapping Between HDF5 Atomic Data Types and MATLAB Data Types for a list of these mappings.
Mapping Between HDF5 Atomic Data Types and MATLAB Data Types
| HDF5 Atomic Data Type | MATLAB Data Type |
|---|---|
| Bit-field | Array of packed 8-bit integers |
| Float | MATLAB single and double types, provided that they occupy 64 bits or fewer |
| Integer types, signed and unsigned | Equivalent MATLAB integer types, signed and unsigned |
| Opaque | Array of uint8 values |
| Reference | Array of uint8 values |
| String | MATLAB character arrays. |
For composite data types, such as aggregations of one or more atomic data types into structures, multidimensional arrays, and variable-length data types (one-dimensional arrays), the mapping is sometimes ambiguous with reference to the HDF5 data type. In HDF5, a 5-by-5 data set containing a single uint8 value in each element is distinct from a 1-by-1 data set containing a 5-by-5 array of uint8 values. In the first case, the data set contains 25 observations of a single value; in the second case, the data set contains a single observation with 25 values. In MATLAB both of these data sets are represented by a 5-by-5 matrix.
If your data is a complex data set, you might need to create HDF5 data types directly to make sure you have the mapping you intend. See the table Mapping Between HDF5 Composite Data Types and MATLAB Data Types for a list of the default mappings. You can specify the data type when you write data to the file using the H5Dwrite function. See the HDF5 data type interface documentation for more information.
Mapping Between HDF5 Composite Data Types and MATLAB Data Types
| HDF5 Composite Data Type | MATLAB Data Type |
|---|---|
| Array | Extends the dimensionality of the data type which it contains. For example, an array of an array of integers in HDF5 would map onto a two dimensional array of integers in MATLAB. |
| Compound | MATLAB structure. Note: All structures representing HDF5 data in MATLAB are scalar. |
| Enumeration | Array of integers which each have an associated name |
| Variable Length | MATLAB 1-D cell arrays |
Reporting Data Set Dimensions. The MATLAB low-level HDF5 functions report data set dimensions and the shape of data sets differently than the MATLAB high-level functions. For ease of use, the MATLAB high-level functions report data set dimensions consistent with MATLAB column-major indexing. To be consistent with the HDF5 library, and to support the possibility of nested data sets and complicated data types, the MATLAB low-level functions report array dimensions using the C row-major orientation.
This example shows how to use the MATLAB HDF5 low-level functions to write a data set to an HDF5 file and then read the data set from the file.
Create the MATLAB variable that you want to write to the HDF5 file. The examples creates a three-dimensional array of uint8 data.
testdata = uint8(ones(5,10,3));
Create the HDF5 file or open an existing file. The example creates a new HDF5 file, named my_file.h5, in the system temp directory.
filename = fullfile(tempdir,'my_file.h5'); fileID = H5F.create(filename,'H5F_ACC_TRUNC','H5P_DEFAULT','H5P_DEFAULT');
In HDF5, you use the H5Fcreate function to create a file. The example uses the MATLAB equivalent, H5F.create. As arguments, specify the name you want to assign to the file, the type of access you want to the file ('H5F_ACC_TRUNC' in the example), and optional additional characteristics specified by a file creation property list and a file access property list. This example uses default values for these property lists ('H5P_DEFAULT'). In the example, note how the C constants are passed to the MATLAB functions as strings. The function returns an ID to the HDF5 file.
Create the data set in the file to hold the MATLAB variable. In the HDF5 programming model, you must define the data type and dimensionality (data space) of the data set as separate entities.
Specify the data type used by the data set. In HDF5, you use the H5Tcopy function to create integer or floating-point data types. The example uses the corresponding MATLAB function, H5T.copy, to create a uint8 data type because the MATLAB data is uint8. The function returns a data type ID.
datatypeID = H5T.copy('H5T_NATIVE_UINT8');
Specify the dimensions of the data set. In HDF5, you use the H5Screate_simple routine to create a data space. The example uses the corresponding MATLAB function, H5S.create_simple, to specify the dimensions. The function returns a data space ID.
dims(1) = 5; dims(2) = 10; dims(3) = 3 dataspaceID = H5S.create_simple(3, dims, []);
Create the data set. In HDF5, you use the H5Dcreate routine to create a data set. The example uses the corresponding MATLAB function, H5D.create, specifying the file ID, the name you want to assign to the data set, data type ID, the data space ID, and a data set creation property list ID as arguments. The example uses the defaults for the property lists. The function returns a data set ID.
dsetname = 'my_dataset'; datasetID = H5D.create(fileID,dsetname,datatypeID,dataspaceID,'H5P_DEFAULT');
Note To write a large data set, you must use the chunking capability of the HDF5 library. To do this, create a property list and use the H5P.set_chunk function to set the chunk size in the property list. In the following example, the dimensions of the data set are dims = [2^16 2^16] and the chunk size is 1024-by-1024. You then pass the property list as the last argument to the data set creation function, H5D.create, instead of using the H5P_DEFAULT value. plistID = H5P.create('H5P_DATASET_CREATE'); % create property list
chunk_size = min([1024 1024], dims); % define chunk size
H5P.set_chunk(plistID, chunk_size); % set chunk size in property list
datasetID = H5D.create(fileID, dsetname, datatypeID, dataspaceID, plistID); |
Write the data to the data set. In HDF5, you use the H5Dwrite routine to write data to a data set. The example uses the corresponding MATLAB function, H5D.write, specifying as arguments the data set ID, the memory data type ID, the memory space ID, the data space ID, the transfer property list ID and the name of the MATLAB variable to be written to the data set.
You can use the memory data type to specify the data type used to represent the data in the file. The example uses the constant 'H5ML_DEFAULT' which lets the MATLAB function do an automatic mapping to HDF5 data types. The memory data space ID and the data set's data space ID specify to write subsets of the data set to the file. The example uses the constant 'H5S_ALL' to write all the data to the file and uses the default property list.
Note Because HDF5 stores data in row-major order and MATLAB accesses data in column-major order, you should permute your data before writing it to the file. |
data_perm = permute(testdata,[3 2 1]);
H5D.write(datasetID,'H5ML_DEFAULT','H5S_ALL','H5S_ALL', ...
'H5P_DEFAULT',data_perm);
Close the data set, data space, data type, and file objects. If used inside a MATLAB function, these identifiers are closed automatically when they go out of scope.
H5D.close(datasetID); H5S.close(dataspaceID); H5T.close(datatypeID); H5F.close(fileID);
To read the data set you wrote to the file, you must open the file. In HDF5, you use the H5Fopen routine to open an HDF5 file, specifying the name of the file, the access mode, and a property list as arguments. The example uses the corresponding MATLAB function, H5F.open, opening the file for read-only access.
fileID = H5F.open(filename,'H5F_ACC_RDONLY','H5P_DEFAULT');
After opening the file, you must open the data set. In HDF5, you use the H5Dopen function to open a data set. The example uses the corresponding MATLAB function, H5D.open, specifying as arguments the file ID and the name of the data set, defined earlier in the example.
datasetID = H5D.open(fileID, dsetname);
After opening the data set, you can read the data into the MATLAB workspace. In HDF5, you use the H5Dread function to read an HDF5 file. The example uses the corresponding MATLAB function, H5D.read, specifying as arguments the data set ID, the memory data type ID, the memory space ID, the data space ID, and the transfer property list ID.
returned_data = H5D.read(datasetID,'H5ML_DEFAULT',...
'H5S_ALL','H5S_ALL','H5P_DEFAULT');Note that the data returned must be indexed in reverse order: HDF5 stores the data in row-major order; MATLAB accesses data in column-major order. To rearrange the data into column-major order, use the MATLAB permute function.
data = permute(returned_data,[3 2 1]);
You can compare the original MATLAB variable, testdata, with the variable just created, data, to see if they are the same.
![]() | Flexible Image Transport System (FITS) Files | Hierarchical Data Format (HDF4) Files | ![]() |
| © 1984-2008- The MathWorks, Inc. - Site Help - Patents - Trademarks - Privacy Policy - Preventing Piracy - RSS |