MATLAB: How to find rank within group

ranking

I have a dataset with 100 different groups, and between 8-11 entries in each group. I want to rank them, within a group, by the value of a variable y. How would I do this?
Concretely, if I have 2 groups with 2 people each such that: y=[1; 3; 6; 5] group_id=[1;1;2;2]
then I want a third vector: rank=[1;2;2;1]

Best Answer

[~,a] = cellfun(@sort,accumarray(group_id,y,[],@(x){x}),'un',0);
rank = cell2mat(a);
or within for..end:
y=[1; 3; 6; 5];
group_id=[1;1;2;2];
rank = group_id;
a = unique(group_id);
for ii = 1:numel(a)
t = group_id == a(ii);
[~,rank(t)] = sort(y(t));
end
Related Question