How to average a column based on another column?

조회 수: 19(최근 30일)
Leon
Leon 2014년 2월 20일
댓글: Leon 2014년 2월 20일
For example, I have a two column data as below:
1945 23.5
1952 25.6
1952 25.9
1952 23.5
1957 26.7
1957 31.2
How do I get a two column data as below, with the left column being the unique numbers: 1945, 1952, 1957, and the second column being the average values of that year:
1945 23.5
1952 25.0
1957 28.95
I can write a loop to do this, but think it must have an easier way to do this.
Thank you@

채택된 답변

Matt Kindig
Matt Kindig 2014년 2월 20일
This is a good use of accumarray():
[ud,ix,iy]=unique( data(:,1));
output = [ud, accumarray(iy,data(:,2),[],@mean)];
  댓글 수: 1
Leon
Leon 2014년 2월 20일
So cool!
Thank you very much.

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

추가 답변(0개)

태그

Community Treasure Hunt

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

Start Hunting!

Translated by