Skip to content

Instantly share code, notes, and snippets.

@shaybensasson
Created March 4, 2015 09:02
Show Gist options
  • Save shaybensasson/b5a0d1f04eb852db42ce to your computer and use it in GitHub Desktop.
Save shaybensasson/b5a0d1f04eb852db42ce to your computer and use it in GitHub Desktop.
Grouping and doing mean
% based on http://stackoverflow.com/questions/22792020/matlab-accumarray-weighted-mean
data = [10 1;30 1;20 2;30 1;20 4;20 6]
%{
data =
10 1
30 1
20 2
30 1
20 4
20 6
%}
data = sortrows(data, 1);
Vals = data(:,2);
[ID, ~, Groups] = unique(data(:,1),'stable')
%{
ID =
10
20
30
Groups =
1
2
2
2
3
3
%}
fnMean = @(ii) mean(Vals(ii));
means = accumarray(Groups, 1:numel(Groups), [], fnMean)
%{
means =
1
4
1
%}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment