this is the data I am working with
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
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));
댓글 수: 0
추가 답변 (2개)
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
댓글 수: 0
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
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 Center 및 File Exchange에서 Dates and Time에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!