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.

 採用された回答

Azzi Abdelmalek
Azzi Abdelmalek 2015 年 7 月 24 日

1 投票

n=4
a=randperm(2*n)
out=a>n

その他の回答 (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 ExchangeRandom 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