How to calculate the accumulated rainfall value of 1, 2, 3, 4, 5, 6 and 7 days.

16 views (last 30 days)
I need to calculate the cumulative rainfall of 1, 2, 3, 4, 5, 6 and 7 days and extract the annual maximum of each year (after accumulation). I have historical series of precipitation with a great amount of years organized as follows: day, month, year, precipitation [mm], each in a column. I tried using the code below but it did not work.
%% Import Precipitation Data
RainMatrix = importdata ('data.txt');
% Identifies the first and last year of the series
First_Year = RainMatrix(1,3);
Last_Year = RainMatrix(end,3);
% Measuring the Data Series Size;
T = length(unique(RainMatrix(:,3)));
P = 2; % Time Step, P = 1, 2, 3, 4, 5, 6 and 7 days
k = 1; % Counter
for ii = 1 : (T-1)
Year = find(RainMatrix(:,3) == First_Year); % Identifies the year
RainMatrix = RainMatrix(Year(:,1),:); % Cut the year
n = length(RainMatrix); % Dimension of Cut Out Data
for i = P : P : n
Rainfall(k,1) = sum(RainMatrix(i-P+1:i,4)); % Cumulative rainfall of "P" days
k = k+1;
[x, y] = ismember(max(Rainfall(:,1)),Rainfall(:,1)); % Find the Maximum Value of the Series
MaxAnual(ii,1) = Rainfall(y);
end
First_Year = First_Year + 1;
Rainfall = [];
end
  4 Comments

Sign in to comment.

Accepted Answer

David Wilson
David Wilson on 20 Apr 2019
Here is my solution:
I notice that you've got few NaNs for about a year and a half. Your last year is also incomplete.
I isolated each year, and then reshaped the data in blocks of 1,2, ... 7. I dropped a few days at the end of the year if they were not exact multiples. I then summed the cols, and then took the max and stored it in an array.
%% Import Precipitation Data
RainMatrix = importdata('data.txt');
% Identifies the first and last year of the series
yr = RainMatrix(:,3); % years
yr1 = yr(1); yr_end = yr(end);
Raincum = NaN(yr_end-yr1+1,7); % placeholder
k=0;
for i=yr1:yr_end % scan each year
k=k+1;
idx = find(yr == i);
yri = yr(idx); r = RainMatrix(idx,4); nr = length(r);
length(yri); % check should be 365 or 366 for full years
Raincum(k,1) = max(r);
for j=2:7
rv = r(1:nr - mod(nr,j));
r2 = reshape(rv,j,length(rv)/j);
r2 = sum(r2);
Raincum(k,j) = max(r2);
end
end
%%
yrs = [yr1:yr_end]';
plot(yrs,Raincum)
legend('1','2','3','4','5','6','7')

More Answers (0)

Community Treasure Hunt

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

Start Hunting!