Average values for duplicates in (:,1)

5 views (last 30 days)
aaron Harvey
aaron Harvey on 12 Oct 2015
Answered: Andrei Bobrov on 12 Oct 2015
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).

Answers (2)

Andrei Bobrov
Andrei Bobrov on 12 Oct 2015
[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 on 12 Oct 2015
Edited: Stephen23 on 12 Oct 2015
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

Categories

Find more on Oceanography and Hydrology in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!