필터 지우기
필터 지우기

How can I find the yearly average with repeating years?

조회 수: 1 (최근 30일)
msstarr
msstarr 2015년 5월 8일
댓글: msstarr 2015년 5월 8일
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에서 Logical에 대해 자세히 알아보기

태그

Community Treasure Hunt

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

Start Hunting!

Translated by