Monthly to annual totals
3 visualizaciones (últimos 30 días)
Mostrar comentarios más antiguos
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 comentarios
Respuestas (2)
ag
el 15 de Sept. de 2024
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 comentarios
Star Strider
el 15 de Sept. de 2024
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 comentarios
Ver también
Categorías
Más información sobre Tables en Help Center y File Exchange.
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!