How can I generate a random matrix with 0's and 1's?
5 views (last 30 days)
Show older comments
Fadugba Jeremiah
on 29 Jul 2017
Answered: Andrei Bobrov
on 29 Jul 2017
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
0 Comments
Accepted Answer
Guillaume
on 29 Jul 2017
cell2mat(arrayfun(@(~) (randperm(m) <= d)', 1:n, 'UniformOutput', false))
would be one way.
2 Comments
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.
More Answers (1)
See Also
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!