How can I get a random 0-1 matrix whose elements sum is equal to a defined number?

1 view (last 30 days)
Hello I am new in Matlab, I habe generated the following random 0-1 matrix:
>> C=randi([0,1],5,3)
C =
1 0 1
0 1 0
0 0 1
1 1 0
0 1 1
And I want that the sum of all the elements i equal to one number, for example 12.
I will really appreciate your help.
Thank you in advance

Answers (1)

Walter Roberson
Walter Roberson on 23 Nov 2015
However, in the specific case of random values that are all either 0 or 1, and you need a fixed sum S and it has to go into an M x N matrix (e.g., 5 x 3) then
samples = [ones(1,S), zeros(1,M*N-S)];
C = reshape( samples( randperm(length(samples)) ), M, N);

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!