Finding the average of every nth row but n is not fixed.

조회 수: 1 (최근 30일)
pavlos
pavlos 2019년 7월 23일
댓글: Stephen23 2019년 7월 24일
Hello,
Consider a nx2 matrix M with
M= [
1 10
1 11
1 20
2 4
2 9
2 8
2 7
.
.
.
];
How to find the average of the second column when the first column change values, i.e. "1 rows" have 3
values while "2 rows" have 4, etc. so we need the average of the 3 first values, then the next four, etc.
Thank you.

채택된 답변

Stephen23
Stephen23 2019년 7월 23일
편집: Stephen23 2019년 7월 23일
>> M = [1,10;1,11;1,20;2,4;2,9;2,8;2,8];
Method one: accumarray:
>> V = accumarray(M(:,1),M(:,2),[],@mean)
V =
13.667
7.25
Method two: splitapply:
>> V = splitapply(@mean,M(:,2),M(:,1))
V =
13.667
7.25
And if you want those values back in the matrix:
>> M(:,3) = V(M(:,1))
M =
1 10 13.667
1 11 13.667
1 20 13.667
2 4 7.25
2 9 7.25
2 8 7.25
2 8 7.25
  댓글 수: 2
pavlos
pavlos 2019년 7월 23일
@ Stephen
Thank you, it works perfectly.
But I didn`t mentioned in my question that the values of the 1st column are repeated.
Actually, the 1st column corresponds to hours in a day within a month so, 0,1,..,23 are repeated:
0 0 1. . .23 23 23 1st day
0 1 1...23 2nd day
etc.
So each day has different number of hourly values.
Pavlos
Stephen23
Stephen23 2019년 7월 24일
@pavlos: Then to use this method you will have to generate a unique index for each group that you want to average. You could use findgroups or discretize or the third output from unique (possibly with the 'rows' option) or something similar.

댓글을 달려면 로그인하십시오.

추가 답변 (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