how to find the index of first n occurrence of each unique value of a matrix

I have a 5915x1 matrix and there are 42 unique values in the matrix.I want to find out first 75 occurences of each unique value. suppose i have a column matrix A as
A={1 2 3 4 1 1 2 2 5 5 5 5 4 6 7 8 4 6 4 }
Then for 1 : [1,5,6]
2:[2,7,8]
etc.

1 Comment

Just to clarify: The elements are not unique, otherwise you cannot find 75 occurrences.

Sign in to comment.

 Accepted Answer

A=randi(42,5915,1);
b=cell2mat(arrayfun(@(x) find(A==x,75),1:42,'un',0))'

2 Comments

Hey will it not work for a double array.Coz its giving me an empty matrix as a result :(

Sign in to comment.

More Answers (1)

A = randi(8,20,1); % eg
n = 4;
A1 = unique(A)
na = numel(A1);
out = [A1(:).';nan(n,na)];
for j1 = 1:na
k = find(A == A1(j1),n);
out(2:numel(k)+1,j1) = k;
end
out = out.';

Products

Community Treasure Hunt

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

Start Hunting!