Generate random binary matrix
Mostra commenti meno recenti
Given the number of nodes M and number of links, I want to generate a random M by N matrix with 0 and 1 entries but with the constraints that the sum of each row is a random integer between 1 and L, and the sum of each column is a random integer between 1 and S. Here L and S are integers greater than 1.
Thanks for any hint and help.
David
Risposte (2)
Jos (10584)
il 16 Ott 2013
Should all possibilities of such a matrix be equally likely? Then it might be very quite tricky.
Here's a brute force approach, that might not always work for specific values of S, L, M and N:
M = 5 ; N = 6 ;
S = 3 ; L = 2 ;
% fix the number of 1's per row
X = zeros(M,N) ;
sumRow = ceil(S*rand(M,1)) ;
for k=1:M,
X(k,1:sumRow(k)) = 1 ;
end
ntries = 0 ;
while ntries < 1000 ;
ntries = ntries + 1 ;
% randomly swap columns, see RANDSWAP on the File Exchange
for k=1:M,
p = randperm(N) ;
X(k,:) = X(k,p) ;
end
if all(sum(X,1) <= L) && all(sum(X,1)>0)
break ;
end
end
if ntries < 1000
disp(X)
sumCol = sum(X,1)
sumRow = sum(X,2).'
else
disp('No matrix found within a reasonable time') ;
end
Jan
il 16 Ott 2013
0 voti
You can try a "shooting method":
- Start with a matrix of zeros
- Determine a line and column, which differ the most from the criteria
- Set a 1 there
- Loop
A genetic algorithm might be fine also:
- Start with 100 random matrices
- Select the 10 with the smallest sum of deviations from the criteria
- For each of them create 10 children by setting 10% (and 9% later etc) of the elements randomly
- Perhaps some cross-overs of blocks between the best individuals
- Loop to 2.
Categorie
Scopri di più su Random Number Generation in Centro assistenza e File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!