MATLAB Answers

How to process multiple Excel files using the same Matlab code for each

6 views (last 30 days)
I am currently using Matlab 2020a. I have a code that runs perfectly and it creates a figure for the analysis of the excel file that I have imported (using the function xlsread). However, I have multiple excel files that need to be processed using exactly the same code and I dont want to be changing the names of the files within the code one by one. How can I process them all at once?
My current code looks like this:
function Data()
[NODE2_num,NODE2_text] = xlsread('NODE2.WDH.csv', 'A1:D80421');
datenumColumn = NODE2_num(:,1);
NODE2_2020 = NODE2_num(datenumColumn>=737791, :); %737791 = all year 2020
NODE2_May2020 = NODE2_num(datenumColumn>=737912, :); %737912 = just May
NODE2_28May2020 = NODE2_num(datenumColumn>=737939, :); %737939 = just May 28 (last day of the set of data)
% Create Figure 1 for all data from NODE 2
t = tiledlayout(1,3,'TileSpacing','Compact','Padding','Compact');
% Tile 1
nexttile
x = NODE2_2020(:,1);
y = NODE2_2020(:,2);
plot(x,y,'k-');
title('For 2020')
hold on;
plot((NODE2_2020(:,1)),NODE2_2020(:,3),'b-');
datetick('x','mmm','keeplimits')
tstart = NODE2_2020(1,1);
tend = NODE2_2020(size(NODE2_2020,1),1);
xlim([tstart tend])
xlabel('Month','FontWeight','bold')
% Tile 2
nexttile
plot((NODE2_May2020(:,1)),NODE2_May2020(:,2),'k-')
title('For May, 2020')
hold on;
plot((NODE2_May2020(:,1)),NODE2_May2020(:,3),'b-')
datetick('x','dd','keeplimits')
tstart = NODE2_May2020(1,1);
tend = NODE2_May2020(size(NODE2_May2020,1),1);
xlim([tstart tend])
xlabel('Day','FontWeight','bold')
% Tile 3
nexttile
L(1) = plot((NODE2_28May2020(:,1)),NODE2_28May2020(:,2),'k-','LineWidth',1.5);
title('For May 28, 2020')
hold on
L(2) = plot((NODE2_28May2020(:,1)),NODE2_28May2020(:,3),'b-','LineWidth',1.5);
datetick('x','HHPM','keeplimits','keepticks')
tstart = NODE2_28May2020(1,1);
tend = NODE2_28May2020(size(NODE2_28May2020,1),1);
xlim([tstart tend])
xlabel('Hour','FontWeight','bold')
hold off
title(t,'Acc Data from Node 2')
ylabel(t,'Frequency [Hz]')
lb1 = NODE2_text{1,3};
lb2 = NODE2_text{1,4};
[~,hObj] = legend([L(1),L(2)],{lb1,lb2},'Location','bestoutside','FontSize',10,'LineWidth',1);
hL = findobj(hObj,'type','line');
set(hL,'linewidth',2)
% Save Figure
saveas(gcf, 'Acc Data Node 2.png')
end

  0 Comments

Sign in to comment.

Accepted Answer

the cyclist
the cyclist on 2 Jul 2020
If you can make a cell array of the filenames, eg.
filenames = {'this file.csv','that file.csv','oh this file too.csv'}
then you can write a loop over that cell array:
for fn = filenames
xlsread(fn{:}, 'A1:D80421');
end
If you need to pull the file names from the directory, then you can use the what or ls commands.

More Answers (0)