List all datasets and groups of an hdf5 file

34 views (last 30 days)
Hello!
I am trying to compile all group names and dataset names into a couple cell arrays from an hdf5 file. In python i can accomplish something similar using the visit command. It looks like the low level Matlab comands do contain a visit function as well, but I may not be using it correctly.
Edit: I wanted to clarify there are nested groups/datasets in the file, so recursion is needed to traverse the hdf5 objects.
% Python example for getting all datasets:
keys = []
with h5py.File(filepath, 'r+') as f:
f.visit(lambda key : keys.append(key) if isinstance(f[key], h5py.Dataset) else None)
I tried the following code but it's returning all keys as groups, even though some of them are datasets.
s = struct
s.datasets = {};
s.groups = {};
fid = H5F.open(fileName, 'H5F_ACC_RDONLY', 'H5P_DEFAULT');
[status sOut] = H5O.visit(fid, 'H5_INDEX_NAME', 'H5_ITER_NATIVE', @getObjInfo, s);
function [status, sOut] = getObjInfo(objId, name, sIn)
obj_info=H5O.get_info(objId);
disp(obj_info.nlinks)
switch(obj_info.type)
case H5ML.get_constant_value('H5G_LINK')
fprintf('Object #%s is a link.\n', name);
case H5ML.get_constant_value('H5G_GROUP')
fprintf('Object #%s is a group.\n', name);
sIn.groups{end+1} = name;
case H5ML.get_constant_value('H5G_DATASET')
fprintf('Object #%s is a dataset.\n', name);
sIn.datasets{end+1} = name;
case H5ML.get_constant_value('H5G_TYPE')
fprintf('Object #%s is a named datatype.\n', name);
end
status = 0; % keep iterating
sOut = sIn;
end
  1 Comment
Walter Roberson
Walter Roberson on 22 Jan 2023
Out of curiosity, what happens if you put the case for H5G_DATASET before the case for H5G_GROUP ?

Sign in to comment.

Accepted Answer

LostInMatlabtion
LostInMatlabtion on 22 Jan 2023
Moved: Walter Roberson on 22 Jan 2023
Looks like it works if i change to the following:
function [status, sOut] = getObjInfo(rootID, name, sIn)
objID = H5O.open(rootID, name, 'H5P_DEFAULT');
obj_info=H5O.get_info(objID);
H5O.close(objID);

More Answers (0)

Tags

Products


Release

R2022a

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!