Generating a random binary matrix with conditions
3 Ansichten (letzte 30 Tage)
Ältere Kommentare anzeigen
Christy Jackson
am 5 Aug. 2016
Kommentiert: Image Analyst
am 5 Aug. 2016
Hello
I have written the following line of code to generate a random binary matrix
Pop = round(rand(5,5))
It works fine in most cases however sometimes i get columns with all zeros, how do i avoid getting all zeros in any of the column.
0 Kommentare
Akzeptierte Antwort
John D'Errico
am 5 Aug. 2016
Just throw those columns away, if you get any like that, and replace them with new samples. WTP?
6 Kommentare
Guillaume
am 5 Aug. 2016
Bearbeitet: Guillaume
am 5 Aug. 2016
But as the size of the matrix increases, the likelihood of getting a whole column of zero decreases (dramatically!), so John answer is even more valid.
The likelyhood of getting a whole column of zero in a 100x100 matrix is 100/2^100 ~ 1 in 1e28. In the very unlikely event that it happens, it takes microseconds to generate a new 100x100 matrix.
>> tic;randi([0 1], 100);toc
Elapsed time is 0.000363 seconds.
Weitere Antworten (1)
Azzi Abdelmalek
am 5 Aug. 2016
A=zeros(5)
[n,m]=size(A)
for k=1:m
id=randperm(n,randi(n))
A(k,id)=1
end
4 Kommentare
Image Analyst
am 5 Aug. 2016
Are there no restrictions on the number of "true" points in the array? Or is any number of them okay? Do you specifically want 5000 in a 100x100, or do you want an average of 30% of them to be true? Or any other criteria? Whether you realize it or not, you are specifying the fraction of points, at least on average. Like doing round() will say that on average 50% of them will be true, but it doesn't have to be 50% - it can be anything you want it to be.
Siehe auch
Kategorien
Mehr zu Creating and Concatenating Matrices finden Sie in Help Center und File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!