Consolidating row values from previous column duplicate values.
조회 수: 9 (최근 30일)
이전 댓글 표시
Hi all,
Is it possible to write a script to make MATLAB look at the first two columns of a matrix, and if there are multiple rows where Column 1 and Column 2 have the same values, to put these rows together and sum the corresponding values of a third column.
An example would be like this;
[a x 2;
a x 3;
b x 4;
a y 5;
b y 6;
b y 7;
c y 8]
and so the script will recognize there are two rows with a in column 1 and x in column 2, so it will put them together and add the values in the third row.
So the output would be like this;
[a x 5;
b x 4;
a y 5;
b y 13;
c y 8]
Forgive my bad formatting of the matrix, but any help will be greatly appreciated!
Kind regards
Willem
댓글 수: 2
채택된 답변
the cyclist
2013년 8월 1일
편집: the cyclist
2013년 8월 1일
You need the accumarray function:
A = [1 1 3;
1 1 4;
1 1 7;
1 2 1;
1 2 6;
2 3 5;
3 6 4;
3 6 9;
3 6 3];
[Aunique,i,j] = unique(A(:,[1 2]),'rows');
Asum = accumarray(j,A(:,3),[],@sum);
output = [Aunique,Asum]
댓글 수: 5
the cyclist
2013년 8월 2일
Don't feel bad if accumarray seems confusing. It's doing a pretty complex thing, and I personally never found the documentation for that particular function to be helpful to me.
추가 답변 (2개)
Andrei Bobrov
2013년 8월 2일
편집: Andrei Bobrov
2013년 8월 2일
A = [1 1 3;
1 1 4;
1 1 7;
1 2 1;
1 2 6;
2 3 5;
3 6 4;
3 6 9;
3 6 3]
A(:,end + (1:3)) = randi(10,size(A,1),3);
[a1,ii,ii] = unique(A(:,1:2),'rows');
[i1 j1] = ndgrid(ii,1:size(A,2) - 2);
a2 = A(:,3:end);
out = [a1 accumarray([i1(:),j1(:)],a2(:))];
댓글 수: 0
참고 항목
카테고리
Help Center 및 File Exchange에서 Performance and Memory에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!