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

조회 수: 2 (최근 30일)
pavlos
pavlos 2019년 8월 16일
편집: dpb 2019년 8월 19일
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에서 Matrix Indexing에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by