How to write a numeric attribute as array size scalar to HDF5 files using high level MATLAB HDF5 functions?

I'm writing scalar attributes to a HDF5 file using the MATLAB high level functions. This works well for string type attribute values but for integer or floating point attribute values always result in array size 1 , not in array size scalar. (See figure)
Question: Some of the HDF5 reading tools I use are strict on this format definitions and require scalars. How can I force the HDF5 high level functions to set the array size information in the file to scalar instead of 1 ?
Example code :
Assign value to attribute variable:
aTestField=int32(16);
Check if this is a scalar, this returns 1.
isscalar(aTestField)
Write the attribute to my file:
h5writeatt( myFile,'/','aTestField', aTestField);
However, the result in HDF5 file is array size 1.

 Accepted Answer

h5writeatt doesn't offer lots of options. Use these guys:
fid = H5F.open([hdf5_file],'H5F_ACC_RDWR','H5P_DEFAULT');
gid = H5G.open(fid,"/*/*"); %specify the location of the attribute
typeID = H5T.copy("H5T_NATIVE_INT32"); %see https://api.h5py.org/h5t.html for more options
spaceID = H5S.create("H5S_SCALAR"); %specify it as a scalar
acpl = H5P.create("H5P_ATTRIBUTE_CREATE");
attrID = H5A.create(gid,"attr_name",typeID,spaceID,acpl);
H5A.write(attrID,"H5ML_DEFAULT",attr_value);
%Close everything
H5A.close(attrID);
H5S.close(spaceID);
H5T.close(typeID);
H5F.close(fid);
H5G.close(gid);
H5P.close(acpl);

More Answers (1)

Hi there,
You may consider the following fix of the MATLAB original 'h5writeatt.m' function. Replace the createDataspaceId function with the function provided below. Note that the fix adds a 'isscalar' check for the attribute and create a scalar dataspace instead of calling ‘H5S.create_simple’, which covers the matrix cases. In the original 'h5writeatt.m' there was no distinction for a scalar case, so it was treated as a matrix.
Hope this helps,
George
function dataspace_id = createDataspaceId(attvalue)
% Setup the dataspace ID. This just depends on how many elements the
% attribute actually has.
if isempty(attvalue)
dataspace_id = H5S.create('H5S_NULL');
return;
elseif ischar(attvalue)
if isrow(attvalue)
dataspace_id = H5S.create('H5S_SCALAR');
return
else
error(message('MATLAB:imagesci:h5writeatt:badStringSize'));
end
else
if isscalar(attvalue)
dataspace_id = H5S.create('H5S_SCALAR');
elseif ismatrix(attvalue) && ( any(size(attvalue) ==1) )
rank = 1;
dims = numel(attvalue);
dataspace_id = H5S.create_simple(rank ,dims,dims);
else
% attribute is a "real" 2D value.
rank = ndims(attvalue);
dims = fliplr(size(attvalue));
dataspace_id = H5S.create_simple(rank, dims, dims);
end
end

Products

Release

R2022a

Community Treasure Hunt

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

Start Hunting!