Monthly to annual totals
조회 수: 3 (최근 30일)
이전 댓글 표시
Hello,
I am hoping to convert monthly totals to annual totals using a loop. However, instead of using the calendar year (Jan-Dec) I want to use the water year which runs from October to September. I have a number of time series organised in a structure (468 rows, 1 column) starting from Oct 1960 and ending in Sept 1999.
I have attempted to sum up each 12 consecutive rows (1:12, 13:24 and so on) to get the annual totals but my code (below) is not doing the job (I am not sure what exactly it is doing) and I was hoping I could get some help fixing it. Many thanks!
for k=1:length(varnames)
p=0;
for i=1:39
for months=1:12
p=p+1;
annual_flow.(varnames{k})(i,1)=flow_monthly.(varnames{k})(p,1);
end
end
end
댓글 수: 0
답변 (2개)
ag
2024년 9월 15일
Hi Anna,
To convert monthly totals to annual totals based on a water year (October to September), you will need to sum every 12 consecutive months starting from October. The current code seems to be assigning monthly values to the annual flow, instead of summing them.
Below is the modified code snippet for the required logic:
for k = 1:length(varnames)
p = 0;
for i = 1:39
% Initialize the sum for the current water year
annual_sum = 0;
% Sum the 12 months of the current water year
for months = 1:12
p = p + 1;
annual_sum = annual_sum + flow_monthly.(varnames{k})(p, 1);
end
% Store the sum in the annual_flow structure
annual_flow.(varnames{k})(i, 1) = annual_sum;
end
end
Hope this helps!
댓글 수: 0
Star Strider
2024년 9월 15일
Y = 1960:1999;
M = 1:12;
Data = [[repmat(M(:), numel(Y), 1) repelem(Y(:), numel(M), 1)] randi(100, 480, 5)] % Create Data
idx = reshape(ones(12,1) * (1:numel(Y)+1), [], 1);
idx = idx([4:end-12 end-2:end]);
disp(idx)
DataYr = accumarray(idx, (1:numel(idx)), [], @(x) {Data(x,:)}); % Demonstrate Function Results (Delete Later If Desired)
disp(DataYr{1})
disp(DataYr{2})
disp(DataYr{end-1})
DataYr{end}
DataYrSum = accumarray(idx, (1:numel(idx)), [], @(x) {sum(Data(x,3:end))}); % Calculate Annual Sum
Result = [[Y(:); Y(end)+1] cell2mat(DataYrSum)];
disp(Result)
The accumarray function existed in the 2012 versions of MATLAB. With it, no explicit loops are necessary.
The actual code (after importing the file, or creating the data as I did here) begins with creating the ‘idx’ vector.
.
댓글 수: 0
참고 항목
카테고리
Help Center 및 File Exchange에서 Tables에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!