How can I find the yearly average with repeating years?

4 次查看(过去 30 天)
I have 55170x1 datetime matrix and 55170x1 water_level numeric matrix. The datetime is in years, repeating the same year through many consecutive cells before moving on chronologically. I want to find the mean water level for each year.

采纳的回答

Mohammad Abouali
Mohammad Abouali 2015-5-8
编辑:Mohammad Abouali 2015-5-8
meanYearly=grpstats(waterLevel,year);
EDIT: I really recommend using grpstats, but if somehow you don't want to use it, or if you don't have statistics toolbox then alternatively you can compute mean yearly as follow:
meanYearly= arrayfun( @(yy) mean(waterLevel(year==yy)), unique(year));

更多回答(2 个)

Andrei Bobrov
Andrei Bobrov 2015-5-8
编辑:Andrei Bobrov 2015-5-8
years = sort(randi([2013,2015],10,1));
water_level = randi([20 50],10,1);
[a,~,c] = unique(years);
out = [a,accumarray(c,water_level,[],@mean)];
with loop for..end
[n,ii] = sort(years(:));
water_level2 = water_level(ii);
yrs = years([true;diff(n)~=0]);
m = numel(yrs);
out2 = zeros(m,2);
for jj = 1:m
out2(jj,:) = [yrs(jj), mean(water_level2(yrs(jj) == years))];
end

Image Analyst
Image Analyst 2015-5-8
Well here's one way, though accumarray can take a bit of study to understand what it's doing.
% Create random years in the range 2007 - 2015
years = randi([2007,2015], 100, 1)
% Create water levels in the range 2007 - 2015
water_level = rand(length(years), 1)
% Get the sums in each year.
yearlySums = accumarray(years - min(years) + 1, water_level)
% Count the number of each year.
counts = histcounts(years, [2007:2015+1])
% Divide to get the average in each year.
yearlyAverages = yearlySums ./ counts'
Make sure you know which are row vectors and which are column vectors if you modify this - make them all the same.
  2 个评论
msstarr
msstarr 2015-5-8
编辑:msstarr 2015-5-8
I am not getting the correct answer. Sorry, I am a beginning with using matlab but I do sort of understand your method. Each year isn't consistent with the same amount of values (for example: 2015 has 75 water level points and 2014 only has 36).
Image Analyst
Image Analyst 2015-5-8
Not sure what that means. My code does create values because you did not attach your data so I had to, if I wanted to test my code.
I was afraid you wouldn't understand - accumarray is not some slam dunk obvious function to understand, especially for beginners. So in that case, just do a for loop . It's the dumb, brute force method , but at least it's intuitive and easy to understand and write. If you can't even do a for loop yet, then read this and let us know if you still need help after that.

请先登录,再进行评论。

类别

Help CenterFile Exchange 中查找有关 Dates and Time 的更多信息

标签

Community Treasure Hunt

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

Start Hunting!

Translated by