Aggregating numbers based on first column index

조회 수: 10 (최근 30일)
Mido
Mido 2016년 11월 4일
댓글: Mido 2016년 11월 5일
Hi
I have a matrix as follows
x=[1 3;
1 4;
1 6;
2 5;
2 7;
3 4;
3 11;
3 1;
3 2]
I want to write a code or a loop that aggregates the numbers in the second column for each different number in the first column.
The result should be
y= [1 13;
2 12;
3 18]

채택된 답변

Walter Roberson
Walter Roberson 2016년 11월 4일
[unique_keys, ~, uq_idx] = unique(x(:,1));
totaled_data = accumarray(uq_idx, x(:,2));
y = [unique_keys, totaled_data];
  댓글 수: 1
Mido
Mido 2016년 11월 5일
I am really thankful to you. This solved my problem.

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

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