MATLAB: Chose vectors (from a randomly generated vectors) which does not contain more than two identical elements

identical elementsrandom vector

I am generating a random vector of size 1×50 (using randi with range 1 to 400),several times(lets say 50000 times). But from these random vectors, I will chose only those vectors which does not contain more than two identical elements i.e. a vector having more than two identical elements will be thrown and rest will be saved in row wise matrix form. How to do this generally so that I can use the code for other cases(e.g. not more than four identical elements instead of two etc.)

Best Answer

If I understood correctly, all you have to do is build the histogram of each row and if you more than two values greater than 1 per row you know that you have more than two duplicate elements. The deprecated histc works better for this than the newer histcounts since the former can operate on columns of a matrix (whereas the latter just flattens the matrix):
m = randi(400, 50000, 50); %50000 rows of 50 columns of random values between 1 and 400
mdist = histc(m.', 1:400); %transpose since histc works on columns
toomanydups = sum(mdist > 1) > 2; %more than 2 values whose distribution is greater than 1 ?
%note that toomanydups is a row vector that has as many columns as the rows of m
m(toomanydups, :) = []; %remove the rows with dups.