# how to compute monthly average values using for loop

17 views (last 30 days)
Valerio Gianforte on 27 Apr 2020
Edited: Olawale Ikuyajolu on 28 Apr 2020
Hi everyone,
I have 11 years of data, every day has 4 values and for each years I have 1460 data. Now, I have to compute the mean monthly value for each months of every year. I'm attacching the data and the code. Thank you.
format long g
folderData = 'D:\Valerio\data\An_Energy_ERA5_IPCC\IPCC_ERA5\ACCESS1.0';
filePattern = fullfile(folderData, '*.xlsx');
xlsFiles = dir(filePattern);
nFiles = length(xlsFiles);
%with for loop we open the file with the order that the files have in the folder
for ii = 1:nFiles
filename = fullfile(xlsFiles(ii).folder, xlsFiles(ii).name);
end
IPCC = files(1);
ERA5 = files(2);
%"unique" command need to read one time the multiple same rows
IPCC_data = unique(IPCC{:,1},'rows');
ERA5_data = unique(ERA5{:,1},'rows');
%The strings below are used to take the common data between two files and
%they are take by the same dates
dt_IPCC = datetime([IPCC_data(:,1:3) IPCC_data(:,4)/1E4 repmat([0 0],size(IPCC_data,1),1)]);
dt_ERA5 = datetime([ERA5_data(:,1:4) repmat([0 0],size(ERA5_data,1),1)]);
[~,ia,ie] = intersect(dt_IPCC,dt_ERA5);
tt_IPCC_ERA5 = timetable(dt_IPCC(ia),IPCC_data(ia,5:end),ERA5_data(ie,5:end));
tt_IPCC_ERA5.Properties.VariableNames = {'IPCC','ERA5'};
% TR_95 = timerange('01-Jan-1985 00:00:00','01-Jan-1996 00:00:00');
% tt_95 = tt_IPCC_ERA5(TR_95,:);
start_yy = 1985;
end_yy = 1995;
range_yy = (start_yy:end_yy).';
r_yy = length(range_yy);
E_IPCC = cell(r_yy,1);
E_ERA5 = cell(r_yy,1);
for i = 1:r_yy
s1 = sprintf('01-Jan-%d 00:00:00',1984+i);
s2 = sprintf('01-Jan-%d 00:00:00',1985+i);
TR = timerange(s1,s2);
tt = tt_IPCC_ERA5(TR,:);
tt_IPCC = tt.IPCC;
tt_ERA5 = tt.ERA5;
E_IPCC{i} = tt_IPCC(:,2).*tt_IPCC(:,1).^2;
E_ERA5{i} = tt_ERA5(:,2).*tt_ERA5(:,1).^2;
end
I have to obtaine the mean monthly value of E_IPCC and E_ERA5.

Olawale Ikuyajolu on 28 Apr 2020
Edited: Olawale Ikuyajolu on 28 Apr 2020
%% first create an array with repeating values for all days in a month e.g. Jan =1 for day 1 to 31
a = datenum({'01-Jan-2003';'31-Dec-2003'}); %Satrt and end dates
Out2 = datevec(a(1):1:a(2)); %arrays of dates
aa2 = Out2(:,1:3); % save only yy-mm-dd
mm = aa2(:,2); % save only months
for i= 1:11
temp = E_IPCC{i,1}; % selecting each year in the cell
temp_daily = reshape(temp,[4,length(temp)/4])'; % separate the four daily values
temp_daily_mean = mean(temp_daily,2); % first compute daily mean
for j = 1:12
E_IPCC_monmean(j,i) = mean(temp_daily_mean(mm==j)); %monthly mean
end
end

### Categories

Find more on Introduction to Installation and Licensing in Help Center and File Exchange

R2018b

### Community Treasure Hunt

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

Start Hunting!