How to extract data by looping through struct

19 次查看(过去 30 天)
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).

采纳的回答

Walter Roberson
Walter Roberson 2022-9-13
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 个评论
Walter Roberson
Walter Roberson 2022-9-13
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
Emu
Emu 2022-9-13
I see :) thank you so much that is incredibly helpful ! how would I plot a mean average?

请先登录,再进行评论。

更多回答(1 个)

Emu
Emu 2022-9-13
ok thank you, but I still don't understand how to loop through my data to plot it..?

类别

Help CenterFile Exchange 中查找有关 Structures 的更多信息

产品


版本

R2020b

Community Treasure Hunt

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

Start Hunting!

Translated by