Average values for duplicates in (:,1)

조회 수: 5 (최근 30일)
aaron Harvey
aaron Harvey 2015년 10월 12일
답변: Andrei Bobrov 2015년 10월 12일
Hi, I have written a script with a for loop in it that plots two measurements (water tempurature and salinity) for a given depth and a given x position. There are only 7 different x locations. I have a matix B being produced in a for loop for various depths, a new B for each new depth. Where B=[xdistance,Temp,Sal] e.g
B=
000 14 33
000 14 34
700 13 35
700 13 36
700 12 35 . . .
how can I average B such that there are no duplicates in B(:,1)
B=
000 14 33.5
700 12.67 35.67 ...
without having to specify the length of B as it will change for each depth (each iteration of the for loop).

답변 (2개)

Andrei Bobrov
Andrei Bobrov 2015년 10월 12일
[A,~,ii] = unique(B(:,1),'stable');
x = B(:,[2,3]);
[a,b] = ndgrid(ii,1:2);
A(:,2:3) = accumarray([a(:),b(:)],x(:))./(accumarray(ii,1)*ones(1,size(x,2)));

Stephen23
Stephen23 2015년 10월 12일
편집: Stephen23 2015년 10월 12일
You can use unique and accumarray very efficiently:
B = [...
000 14 33
000 14 34
700 13 35
700 13 36
700 12 35]
[A,~,z] = unique(B(:,1),'stable');
A(:,2) = accumarray(z,B(:,2),[],@mean);
A(:,3) = accumarray(z,B(:,3),[],@mean);
Generates this output matrix:
>> A
A =
0.00000 14.00000 33.50000
700.00000 12.66667 35.33333

카테고리

Help CenterFile Exchange에서 Oceanography and Hydrology에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by