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).
0 个评论
采纳的回答
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
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
更多回答(1 个)
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Structures 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!