Average values for duplicates in (:,1)

2 次查看(过去 30 天)
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 中查找有关 Loops and Conditional Statements 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by