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 Center および File ExchangeShifting and Sorting Matrices についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by