Producing random numbers in Matlab?
显示 更早的评论
How can I produce random binary numbers with exact number of zeros or ones? for example:
[0 1 0 1 0 1 0 0 1 0] ===> number of ones are 4,
[1 1 0 0 1 0 0 1 0 0] ===> again number of ones are 4,
[1 0 0 1 0 0 0 0 0 1] ===> number of ones are 3, which is not allowed.
I just want exact number of ones in output of random sets.
采纳的回答
更多回答(3 个)
Torsten
2015-7-24
x=zeros(10);
[y,idx]=datasample(1:10,4,'Replace',false);
x(idx)=1;
Best wishes
Torsten.
2 个评论
Azzi Abdelmalek
2015-7-24
This doesn't work
Azzi Abdelmalek
2015-7-24
With randi, you can get the same number more then once
Azzi Abdelmalek
2015-7-24
Using rand
n=4
m=6
a=[ones(1,n), zeros(1,m)]
[~,idx]=sort(rand(1,m+n))
out=a(idx)
类别
在 帮助中心 和 File Exchange 中查找有关 Random Number Generation 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!