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

1 次查看(过去 30 天)
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

采纳的回答

dpb
dpb 2019-8-16
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 个评论
pavlos
pavlos 2019-8-17
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 2019-8-18
编辑:dpb 2019-8-19
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.

请先登录,再进行评论。

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Logical 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by