MATLAB: Random Binary Vectors with 14 ones and 14 zeros

binaryrandomset number of onesvector

I need to generate 50 random binary vectors of length 28, with exactly 14 ones and 14 zeros in each vector.
Please help!

Best Answer

This sound like homework, but since there’s a chance it could be part of a legitimate research problem, this is how I would do it:
M = zeros(50,28);
for k1 = 1:50
M(k1,randperm(28,14)) = 1;
end
Sample = M(1:5,:) % Look At First Five Rows
The code begins by preallocating the ‘M’ matrix, then assigning random, non-repeating (in the same row vector) 1 values to each row. See the documentation for randperm for details.