1
\$\begingroup\$

I implemented a simple class container for hdf5 files in matlab.

The situation is as follows. Measurement data is saved in hdf5 format together with a lot of meta data. I want to provide a tool to easily load the table of data to browse though the name and then only load the necessary data with as little overhead (mostly code length wise for the user, but of course also performance) for the user as possible. I came up with this easy solution.

The used Dataformat only delivers data with groupdepth of 1.

classdef h5 < handle
    properties(Access = private)
        % container for the actual values, if empty this means that the
        % value has not been loaded yet. Induvidual fields get loaded
        % during access
        val

        % name of all the fields, this get loaded during construction
        name = {}

        filename
        pfad
    end

    methods
        %% constructor
        function o = h5(pfad)
            info = h5info(pfad);
            o.filename = info.Filename;
            o.pfad = pfad;

            % Add the possible fields to the name array
            for element = info.Datasets'
                o.name{end+1} = element.Name;
            end

            for group = info.Groups'
                for element = group.Datasets'
                    o.name{end+1} = [group.Name(2:end) '/' element.Name];
                end
            end

            o.val = cell(size(o.name));
        end

        %% show the possible values
        function disp(o)
            fprintf('h5 file loaded from %s with the fields:\n\n',o.filename);

            for name = o.name
                fprintf('%s\n',name{1});
            end
        end

        %% get the dataset
        function out = get(o,name)
            pos = strcmp(name,o.name);

            % Does the dataset exist?
            if sum(pos) == 0
                warning('Dataset doesn''t exist')
                out = [];
                return
            end

            % Did we already load it?
            if isempty(o.val{pos})
                o.val{pos} = h5read(o.pfad,['/' o.name{pos}]);
            end

            out = o.val{pos};
        end
    end
end

Do you see any obvious oversights on my sight with this or anything I should change?

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.