MATLAB: Select groups of data with a specific size

same size groupssorting

Dear all,
Imagine you have a matrix with three colums, the first one is a grouping variable and the other two are coordinates (xy).
The grouping variable looks like this
A = [1 1 1 1 2 2 2 3 3 3 3]';
In this way i have four coordinates in the group 1, three coordinates in the group 2 and four in the group 3. I would like to exclude the groups that do not have 4 data points, i.e., more or less than 4 (in this case group 2).

Best Answer

Simply build the histogram of your groups (with histcounts or accumarray) and select the groups you want to keep with ismember:
demodata = [[1 1 1 1 2 2 2 3 3 3 3]', randi(100, 11, 2)]
[group, ~, groupid] = unique(demodata(:, 1));
groupcount = accumarray(groupid, 1); %histogram of groups
keptdata = demodata(ismember(demodata(:, 1), group(groupcount == 4)), :)