MATLAB: Average of consecutively increasing numbers

arrayaverageconsecutive integersmoving averagerun length

I have 4 columns of data in an array. The first three columns are year, month, day. The 4th column is a z-score. I need to compute the average of the 4th column for as long as the date increases by one day. When there is more than a 1 day difference between the dates the average needs to stop so that the average is only of consecutively increasing dates. Then a new average will pick up for the next set of consecutively increasing dates. Here is the first few rows of my data. Column 1 (years) = (1950,1950,1950,1950,1951,1951,1958,1958,1958,1959), Column 2 (month) = (11,11,11,11,3,3,2,2,2,3), Column 3 (day) = (22,23,24,25,11,12,15,16,17,2), and Column 4 (zscore) = (-.7,-.5,-1.1,-1.3,-1.6,-.8,-.5,-1.4,1,.5).

Best Answer

years = [1950,1950,1950,1950,1951,1951,1958,1958,1958,1959]'
month= [11,11,11,11,3,3,2,2,2,3]'
day= [22,23,24,25,11,12,15,16,17,2]'
zscore =[-.7,-.5,-1.1,-1.3,-1.6,-.8,-.5,-1.4,1,.5]'
n=numel(years)
D=[years month day]
idx=[0 ;diff(datenum(D))]
ii=cumsum(not(idx==1))
z=cell2mat(accumarray(ii,(1:size(D,1))',[],@(x) {mean(zscore(x))*ones(numel(x),1)}))
out=[D z]