How do I create a For loop from a string array that will fill and load h5 files?
6 views (last 30 days)
Show older comments
Hello,
I'm working with .h5 files and trying to read them in and export accelerometer data from them for each trial. Every participants has differing amount of trials that they were able to conduct, so I use ls to identify the trials within a subject directory. The problem arises because each .h5 file is named after the day, time and task that it was collected on (example "20230313-085403_Walk.h5"). The entire name of the file is needed to load the h5 files but for some reason I can't wrap my head around this part with h5read. This can range from 5 trials to 30 trials. Any help would be greatly appreciated!
Code:
Trials = ls('*Walk.h5'); % could change ls to DIRFF, but we should be in that folder.
n_Trials=size(Trials,1);
%%% idenitfying all Walk.h5 files in subject directory, creating a vector the size of how many trials there are
for i = 1:length(n_Trials)
%% Loops through as many times there are trials.
Head = h5read({i}, '/Sensors/10075/Accelerometer');
Chest = h5read({i}, '/Sensors/10235/Accelerometer');
Lumbar = h5read('{i}', '/Sensors/10008/Accelerometer');
Right_Foot = h5read('{i}', '/Sensors/10152/Accelerometer');
Left_Foot = h5read('{i}', '/Sensors/10156/Accelerometer');
Right_Wrist = h5read('{i}', '/Sensors/10134/Accelerometer');
%%% Below is unrelated to issue, but to help show where its going.
x = Head(1,385:end);
y = Head(2,385:end);
z = Head(3,385:end);
res1 = sqrt((x.^2)+(y.^2)+(z.^2));
x2 = Chest(1,385:end);
y2 = Chest(2,385:end);
z2 = Chest(3,385:end);
res2 = sqrt((x2.^2)+(y2.^2)+(z2.^2));
x3 = Lumbar(1,385:end);
y3 = Lumbar(2,385:end);
z3 = Lumbar(3,385:end);
res3 = sqrt((x3.^2)+(y3.^2)+(z3.^2));
res_total = padcat(res1, res2, res3);
end
Any help would be greatly appreciated! My apologies if this has been addressed somewhere, but I can't quite find it with the search terms.
2 Comments
Stephen23
on 12 Apr 2023
Do not use LS. Use DIR, as the documentation shows:
"but we should be in that folder."
Rather than restricting your user like that, a much better approach is to use absolute/relative filenames:
Accepted Answer
dpb
on 13 Apr 2023
d=dir('*Walk.h5');
for i = 1:numel(d)
Head = h5read(fullfile(d(i).folder,d(i).name), '/Sensors/10075/Accelerometer');
...
Looks like you could read the metadata from the file first to determine the sizes and then save some manipulations later...as a general rule, don't bury "magic numbers" like the 385 value inside code; if must use absolute addressing (really should try to avoid this), then at least put the number in a variable where it can be fixed in one place instead of scattered all throughout the code.
More Answers (0)
See Also
Categories
Find more on Whos in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!