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
Torsten 2015년 7월 24일

1 개 추천

x=zeros(10);
[y,idx]=datasample(1:10,4,'Replace',false);
x(idx)=1;
Best wishes
Torsten.
david O
david O 2015년 7월 24일
편집: david O 2015년 7월 24일

0 개 추천

x=zeros(10,1,1);
for i=1:4
x(randi(10))=1;
end

댓글 수: 2

Azzi Abdelmalek
Azzi Abdelmalek 2015년 7월 24일
This doesn't work
Azzi Abdelmalek
Azzi Abdelmalek 2015년 7월 24일
With randi, you can get the same number more then once

댓글을 달려면 로그인하십시오.

Azzi Abdelmalek
Azzi Abdelmalek 2015년 7월 24일

0 개 추천

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에 대해 자세히 알아보기

질문:

2015년 7월 24일

답변:

2015년 7월 24일

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by