Effacer les filtres
Effacer les filtres

save a cell to h5 file in matlab

13 vues (au cours des 30 derniers jours)
Georges Murr
Georges Murr le 6 Mai 2021
Réponse apportée : Deepak le 10 Sep 2024 à 6:21
How can I save a 1x2000 cells with each cell is a 21x512 matrix into a h5 file in matlab ? It saves all the cells as 1x2000 double and all of them are zeros. I want to save the cells in h5 file to use it in python, if there is another way to do it please let me know, appreciate your help.
for i = 1:length(idxtrain)
x_train{i} = img_array_prec{idxtrain(i)}(:,:,1);
end
%%
for i = 1:length(idxtest)
x_test{i} = img_array_prec{idxtest(i)}(:,:,1);
end
%%
savefileh5 = 'traintest.h5'
%%
try
h5create(savefileh5,'/train/x_train',[size(x_train,1) size(x_train,2)]);
h5write(savefileh5,'/train/x_train',x_train);
catch ME
warning('File already in folder');
end
%%
x_train1 = h5read(savefileh5,'/train/x_train'); %it gives double

Réponses (1)

Deepak
Deepak le 10 Sep 2024 à 6:21
Hi Georges,
To my understanding, you have generated a 1x2000 dimension cell array, with each cell being a matrix of size 21x512. Now, you want to save the cell array to an H5 file to use it in python; however, you are getting a 1x2000 double array with all zeroes in the h5 file.
Upon investigating, I found that the cell array needs to be converted to a 3D numeric array with dimension 21 x 512 x 512, as the H5 file stores the numeric arrays, and not cell arrays. Finally, the generated 3D arrays, both for test and train data, can be passed to “h5create” and “h5write” functions to save data to the H5 file.
Below is the updated MATLAB code with all the required modifications:
% Convert cell arrays to 3D arrays
x_train_array = cat(3, x_train{:});
x_test_array = cat(3, x_test{:});
savefileh5 = 'traintest.h5';
% Save x_train
try
h5create(savefileh5, '/train/x_train', size(x_train_array), 'Datatype', 'double');
h5write(savefileh5, '/train/x_train', x_train_array);
catch ME
warning('File already in folder or dataset already exists');
end
% Save x_test
try
h5create(savefileh5, '/test/x_test', size(x_test_array), 'Datatype', 'double');
h5write(savefileh5, '/test/x_test', x_test_array);
catch ME
warning('File already in folder or dataset already exists');
end
% Read back the data to verify
x_train_read = h5read(savefileh5, '/train/x_train');
x_test_read = h5read(savefileh5, '/test/x_test');
disp(size(x_train_read));
disp(size(x_test_read));
Please find attached the documentations of “cat” and “h5create” functions in MATLAB for reference:
I believe this will help to resolve the issue.

Catégories

En savoir plus sur Environment and Settings dans Help Center et File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by