How do I average rows which contain the same first to elements?

조회 수: 2 (최근 30일)
Glenn Roumen
Glenn Roumen 2013년 6월 10일
I'm stuck on this problem for a while. I want to obtain a matrix which is averaged for the rows which contain the same first two elements. I don't want to clear the rows which are not equal for the first two elements. When I have a matrix A:
A=[1 1 1 1 1
1 2 3 4 5
1 2 4 4 4
1 2 3 3 3
2 2 2 2 2
2 2 3 3 3]
I want the outcome to be:
A=[1 1 1 1 1
1 2 3.33 3.67 4
2 2 2.5 2.5 2.5]
I hope someone could help me on this.

채택된 답변

Ahmed
Ahmed 2013년 6월 10일
This solution is not very elegant, but should work. There is room for improvement, though.
uA = unique(A(:,1:2),'rows');
A = [uA cell2mat(cellfun(@(x)...
mean(A(all(bsxfun(@eq,A(:,1:2),x),2),3:end),1), ...
num2cell(uA,2),...
'UniformOutput',false)) ]

추가 답변 (1개)

Andrei Bobrov
Andrei Bobrov 2013년 6월 10일
편집: Andrei Bobrov 2013년 6월 10일
[~,~,c] = unique(A(:,1:2),'rows');
out = accumarray([repmat(c,size(A,2),1) kron((1:size(A,2))',...
ones(size(A,1),1))],A(:),[],@mean);
or
[c c c] = unique(A(:,1:2),'rows');
[ii,jj] = ndgrid(c,1:size(A,2));
out = accumarray([ii(:) jj(:)],A(:),[],@mean);

카테고리

Help CenterFile Exchange에서 Creating and Concatenating Matrices에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by