MATLAB: Unique of two columns and average of the third column

averageunique

I have a data that looks like this –
1.000000 3.000000 12.772348
1.000000 3.000000 295.544610
1.000000 5.000000 121.180790
1.000000 5.000000 141.528104
1.000000 6.000000 253.601575
1.000000 6.000000 74.807279
1.000000 7.000000 69.999278
2.000000 10.000000 48.205100
2.000000 11.000000 267.308963
2.000000 11.000000 78.648585
2.000000 12.000000 125.921451
2.000000 12.000000 52.058998
2.000000 12.000000 82.227857
I want to extract out the unique values in 1st and 2end column and mean of z value for repeating values in the 1st and 2end column in the 3th column. Like –
1.000000 3.000000 154.158479
1.000000 5.000000 131.354447
1.000000 6.000000 164.204427
1.000000 7.000000 69.999278
2.000000 10.000000 48.205100
2.000000 11.000000 172.978774
2.000000 12.000000 86.736102
Can someone please help me with this .. Thanks..

Best Answer

Prefer to post the data such that the users can copy&paste them without the need of further editing - then posting an answer does not demand for tedious editing:
Data = [1 3 12.772348; ...
1 3 295.54461; ...
1 5 121.18079; ...
1 5 141.528104; ...
1 6 253.601575; ...
1 6 74.807279; ...
1 7 69.999278; ...
2 10 48.2051; ...
2 11 267.308963; ...
2 11 78.648585; ...
2 12 125.921451; ...
2 12 52.058998; ...
2 12 82.227857];
Using findgroups and splitapply:
[G, D1, D2] = findgroups(Data(:,1), Data(:,2));
M = splitapply(@mean, Data(:, 3), G)
Result = [D1, D2, M];
Or with accumarray:
[K, ~, G] = unique(Data(:, 1:2), 'rows');
Result = [K, accumarray(G, Data(:, 3), [], @mean)]