Export averaged values from excel according to event
2 views (last 30 days)
Show older comments
I would like to average and export values from excel according to a defined event/category.
Specifically, every time there is an event in column B (represented in the attached doc as [h]) I would like to average the values for columns I and K until the next event. I would then like to repeat this process between each event until the end of the experiment and export the averaged values to a separate .csv file. I would also like to repeat this process for multiple .xlsx files in a folder.
Could someone please advise if this is possible? Thanks MATLAB community!
0 Comments
Accepted Answer
Voss
on 3 Aug 2023
your_folder = '.';
output_file_name = './master_averages.csv';
output_var_names = {'Start_Time','End_Time','I_avg','K_avg'};
S = dir(fullfile(your_folder,'*.xlsx'));
ffn = fullfile({S.folder},{S.name});
cols = [9 11]; % I'm assuming all files have the same column order
T_new = cell(1,numel(ffn));
for jj = 1:numel(ffn)
T = readtable(ffn{jj},'VariableNamingRule','preserve');
event_rows = find(strcmp(T{:,2},'h'));
N_events = numel(event_rows);
event_rows(end+1) = size(T,1)+1;
data = NaN(N_events,4);
for ii = 1:N_events
data(ii,:) = [T{event_rows(ii+[0 1])+[0;-1],1}.' ...
mean(T{event_rows(ii):event_rows(ii+1)-1,cols},1)];
end
T_new{jj} = array2table(data,'VariableNames',output_var_names);
[~,fn,ext] = fileparts(ffn{jj});
T_new{jj}.file = repmat({[fn ext]},size(T_new{jj},1),1);
T_new{jj} = T_new{jj}(:,[end 1:end-1]);
end
T_new = vertcat(T_new{:});
writetable(T_new,output_file_name);
% check
disp(readtable(output_file_name))
More Answers (0)
See Also
Categories
Find more on Spreadsheets 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!