Hi all. I have hourly precip data that I am trying to sum into separate storm events. 24 hours of no precipitation (or 24 zero values) signify the end of the storm event. I'm trying to create a code that sums the precip values until the 24 hours of no rainfall and then starts summing the following storm event. The output will be an array with individual storm event depths of the time series. Does anyone have any suggestions the best method to do this?
Well if you have the Image Processing Toolbox you can get it in 4 lines: a line to identify rain-free hours. Another line to get rid of small stretches of no rain and combine storms on either side into a single storm. The third line to identify stretches of hourly measurements as individually numbered storms, and the fourth line to actually do the measurements of each numbered storm. Here's the code:
rain = rand(1, 50) zeroIndices = rain<0.5; rain(zeroIndices) = 0 % Now we have some sample data % Let's start the analysis:
%======================================================== % Key part right here: % Find out where it's zero (no rain): binaryData = rain == 0 % Get rid of small stretches 2 or less in length: % Change 3 to 24 if you want to combine storms 23 hours or closer together. rainFreeHours = bwareaopen(binaryData, 3) % Now rain-free = 1 and raining = 0. % Invert it to find rainy stretches, then label it to find individual storms. [labeledStorms numStorms] = bwlabel(~rainFreeHours) % Now call regionprops to get the amount of rain over % all hours of each storm: measurements = regionprops(labeledStorms, rain, 'PixelValues'); %========================================================
% We're done! %Now report results for storm = 1 : numStorms rainInThisStorm(storm) = sum(measurements(storm).PixelValues); fprintf('Rainfall total in storm #%d = %.4f\n', ... storm, rainInThisStorm(storm)); end % For fun, report the rain over ALL the hours. totalRainOverAllHours1 = sum(rain) totalRainOverAllHours2 = sum(rainInThisStorm) % Will be the same.
You can use basic MatLab stuff for this too.
Convolution will detect stretches of no rainfall.
dry = conv(rainfall, ones(1,24), 'valid') == 0;
You can then detect rain->dry events with diff (dry changes from 0 to 1)
stormEnd = find(diff(dry) == 1) + 1;
That will give you the index of the first dry hour after each storm.
Now you just treat your data as a series of events. Chuck the first and last index of rainfall in there.
evt = [1, stormEnd, numel(rainfall)];
And sum the rainfall between each event:
totals = arrayfun( @(n) sum(rainfall(evt(n-1):evt(n))), 2:numel(evt) );
Play games and win prizes!Learn more