Finding the sum of every nth row ( n is not fixed)

1 view (last 30 days)
Hello,
Consider a nx2 matrix M with
M= [
0 4
1 10
1 11
1 20
2 4
2 9
2 8
2 7
.
23 8
23 6
0 8
0 7
1 2
2 5
.
.
];
The 1st row refers to hours of the day, i.e. 0,1,...,23
The values of hours per sequence varies, for example the 1st sequence (1st day) has
1 "0"
3 "1" etc
while the 2nd sequence (2nd day) has
2 "0"
1 "1"
etc.
I need to find the sum of the 2nd column per hour and per day.
For example, for the 1st day
4 (for "0")
41 (for "1")
etc.
and for the 2nd day
15 (for "0")
2 (for "1")
etc.
Thank you very much
Best,
Pavlos

Accepted Answer

dpb
dpb on 16 Aug 2019
You'll have to introduce a day variable...by locating the positions where the hour returns to 0 if is always a 0-hour reading or when the diff() is <0 if not; then fill between those with either an arbitrary day (but sequential) number or an actual date if have it.
Once that's done,
[g,da,hr]=findgroups(M(:),M(:)); % grouping variable by day, hour
tot=splitapply(@sum,M(:,3),g); % sum by group
res=table(da,hr,tot); % assemble results in table
the above assumes the day number is prepended to M as the first column.
  2 Comments
pavlos
pavlos on 17 Aug 2019
Thank you for your response.
I get the following error
"Index in position 2 exceeds array bounds (must not exceed 2)."
when applying the tot=splitapply(@sum,M(:,3),g);
dpb
dpb on 18 Aug 2019
Edited: dpb on 19 Aug 2019
As noted, I presumed you introduced the new and needed day variable as column one into your array M so it subsequently has three, not two columns.

Sign in to comment.

More Answers (0)

Categories

Find more on Shifting and Sorting Matrices 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!