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 Center および File ExchangeOceanography and Hydrology についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by