How can I generate a random matrix with 0's and 1's?

5 views (last 30 days)
Any help on generating a random matrix populated with zeros and ones, having exactly d =m/s ones per column, the locations of which are chosen uniformly from [m] without replacement. where m is the number of rows and s is from {1,...,m}. d must be an integer.
I have tried using randerr(m,n,d) but I can not get the desired output. Thanks

Accepted Answer

Guillaume
Guillaume on 29 Jul 2017
cell2mat(arrayfun(@(~) (randperm(m) <= d)', 1:n, 'UniformOutput', false))
would be one way.
  2 Comments
Fadugba Jeremiah
Fadugba Jeremiah on 29 Jul 2017
Thanks this does what I needed but can you explain them a bit to me. Matlab documentation of cell2mat has only 1 parameter but here I'm seeing 4. thanks
Guillaume
Guillaume on 29 Jul 2017
cell2mat only has one argument: the output of arrayfun. arrayfun is used to create a cell array of n columns. Each column generated with (randperm(m) <= d)'. This randperm generates integers from 1 to m, shuffle them and change 1 to d to 1 and the others to 0. The whole thing is equivalent to:
output = zeros(m, n);
for column = 1:n
output(:, column) = randperm(m) <= d;
end
If you prefer an explicit loop.

Sign in to comment.

More Answers (1)

Andrei Bobrov
Andrei Bobrov on 29 Jul 2017
[~,ii] = sort(rand(m,n));
out = ii <= d;

Categories

Find more on Creating and Concatenating Matrices in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!