Carry out the sum of all Januarys, Februarys through December in a range of years

조회 수: 7 (최근 30일)
I have this function that performs the monthly sum of the days of the months, that is, from the 1st to the 31st of January 2000, it adds up the data referring to these days of the month. It is like this for the other months and the other years until 2021.
My goal is to perform the sum of Januarys, Februarys, March and so on for the rest of the months of the year.
For example:
Jan 2000 + Jan 2001 + Jan 2002 + ... Jan 2021 = TOTAL OF ALL JANUARY
Feb 2000 + Feb 2001 + Feb 2002 + ... Feb 2021 = TOTAL OF ALL FEBRUARY
.
.
.
Dec 2000 + Dec 2001 + Dec 2002 + ... Dec 2021 = TOTAL OF ALL DECEMBER
If anyone has any ideas, I'd be very grateful!
function Y = monthly_sum(T, X)
grp = [datenum(2000, 1:252, 1), Inf];
ngrp = numel(grp) - 1;
c = size(X, 2);
X_hour = nan(ngrp, c);
for i = 1:ngrp
for j = 1:c
TX = X(T >= grp(i) & T < grp(i+1), j);
if ~isempty(TX)
X_hour(i,j) = nansum(TX);
end
end
end
Y = [grp(1:ngrp).', X_hour];
end

채택된 답변

Augusto Gabriel da Costa Pereira
times = datetime('1990-01-01'):days(1):datetime('2020-12-31');
Table = timetable(times', rand(length(times), 1), rand(length(times), 1));
Table_monthly = retime(Table, 'monthly', 'sum');
months_order = month(Table_monthly.Time);
all_month_sum = ...
cell2mat(splitapply(@(x) {sum(x, 1)}, Table_monthly.Variables, months_order));
all_month_sum(months_order(1:12), :) = all_month_sum;

추가 답변 (1개)

Simon Chan
Simon Chan 2023년 1월 10일
Read about groupcounts with groupbins "monthname".

카테고리

Help CenterFile Exchange에서 Weather and Atmospheric Science에 대해 자세히 알아보기

제품


릴리스

R2021a

Community Treasure Hunt

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

Start Hunting!

Translated by