How to extract data by looping through struct
19 views (last 30 days)
Show older comments
Hi - I have some data saved as .mat files and i am trying to load it in (think I have done this) and then loop through the data in the struct to plot it all on the same graph (to then plot the mean average also.) Here is my script that doesn't work:
S = dir(fullfile(outputDir,'*.mat'));
fields = fieldnames(S)
for k = 1:length(fields)
F = fullfile(outputDir,S(k).name);
S(k).data = load(F);
S.(fields{k});
%a = table2array(readtable(strcat(S(outputFolders).folder,'/', S(outputFolders).name)));
for j= 1:length(S.data);
%for i = 1:length(preSumTypesoutput)
plot([-6 -5 -4 -3 -2 -1], data(:,i)); hold on;
xticks([-6 -5 -4 -3 -2 -1])
ylim([0 10])
ylim([0 5])
title('Pre-arousal vocalisations')
end
end
and I attach some example data (I am trying to plot 6 of these).
0 Comments
Accepted Answer
Walter Roberson
on 13 Sep 2022
S = dir(fullfile(outputDir,'*.mat'));
S is the output of dir()
fields = fieldnames(S)
The field names returned by dir() include such items as 'name', 'folder', 'bytes', 'isdir' and so on.
for k = 1:length(fields)
You want to loop over the directory structure... unusual, but maybe there is a reason
F = fullfile(outputDir,S(k).name);
You are using the field name index for the directory structure, and using it to index the struct array returned by dir() . If you wanted to loop over the fields of S you would need to use something like
thisfield = {S.(fields{K})};
3 Comments
Walter Roberson
on 13 Sep 2022
S = dir(fullfile(outputDir,'*.mat'));
filenames = fullfile({S.folder}, {S.name});
num_files = length(filenames);
tiledlayout('flow');
for K = 1 : num_files
thisfile = filenames{K};
[~, basename, ~] = fileparts(thisfile);
datastruct = load(thisfile);
data = datastruct.preSumTypesoutput; %fixed field name!!
nexttile();
plot([-6 -5 -4 -3 -2 -1], data);
xticks([-6 -5 -4 -3 -2 -1])
ylim([0 10])
ylim([0 5])
title("Pre-arousal vocalisations for " + basename)
end
More Answers (1)
See Also
Categories
Find more on Structures 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!