cumsum function for seperate time
4 views (last 30 days)
Show older comments
Hi
I have 2 data colomn. 1-colomn time in a form(01/01/1975, 05/01/1975, 25/01/1975, 05/02/1975,...., 22/11/2015), second colomn constant values corresponding to the time(75, 25, 30, 70,..., 55). I wanted to calculate monthly cumulative sum values.Such as for 1-month sum value should appear as 130(75+25+30). And sequences continue...
How I may do it?
Thanks!
0 Comments
Answers (1)
Are Mjaavatten
on 13 Aug 2016
Interesting problem. Here is one possible solution:
dates = {'01/01/1975'; '05/01/1975'; '25/01/1975'; '05/02/1975';...
'15/02/1975';'12/03/1975';'17/02/1978'};
data = [75;25;30;70;32;24;49];
time = datenum(dates,'dd/mm/yyyy'); % Convert strings to Matlab dates
[Y,M] = datevec(time); % Extract year and month vectors
mnthno = Y*12+M; % Unique value for every month
[C,ia] = unique(mnthno); % List of unique months
sums = zeros(size(C)); % Allocate space for the sums
for i = 1:length(C)
sums(i) = sum(data(mnthno==C(i))); % Sum data for each month
% Display results:
fprintf('Year: %4d, Month = %2d, sum = %6.2f \n',...
Y(ia(i)),M(ia(i)), sums(i));
end
You should type
doc datenum
doc datevec
doc unique
if you are not sure what the different functions do.
0 Comments
See Also
Categories
Find more on Dates and Time in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!