Clear Filters
Clear Filters

how to generate a RANDOM matrix of 0's and 1's such that the number of 1's in any column is the same.

2 views (last 30 days)
The positioning of 0's and 1's across the matrix should be random. At the same time, the number of 1's should be fixed. Something like this {1 0 1 0 1 0; 0 1 0 1 0 0; 1 0 1 0 1 0; 0 1 0 1 0 1; 0 0 0 0 0 1 0 0 0 0 0 0} I tried using randperm randi .but I am not getting equal number of 1's Thanks in advance

Accepted Answer

Azzi Abdelmalek
Azzi Abdelmalek on 15 Aug 2016
Edited: Azzi Abdelmalek on 15 Aug 2016
n=6
A=zeros(n)
m=2 % number of 1 per column
for k=1:n
idx=randperm(n,m)
A(idx,k)=1
end

More Answers (2)

José-Luis
José-Luis on 15 Aug 2016
numCol = 5;
numOnes = 3;
numRows = 10;
result = ones(numRows,numCol);
for ii = 1:numCol
result(:,ii) = randperm(numRows) <= numOnes;
end

Azzi Abdelmalek
Azzi Abdelmalek on 15 Aug 2016
n=6
m=2
A=zeros(n)
A(cell2mat(arrayfun(@(x) randperm(n,m)+6*x,0:n-1,'un',0)))=1

Categories

Find more on Random Number Generation 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!