How to create Random Binary Number with fix amount of 1 and 0?

6 ビュー (過去 30 日間)
Camie
Camie 2022 年 7 月 22 日
回答済み: Voss 2022 年 7 月 22 日
Hi all, I need help to create a random binary numbers (length of 30), but there should be only four "1" in it.
Appreciate if anyone can help me on this.
Thank you

回答 (2 件)

Mohammad Sami
Mohammad Sami 2022 年 7 月 22 日
You can try the following.
bin_len = 30;
num_1 = 4;
n = 100;
binfunc = @(~)sum(pow2(randperm(bin_len,num_1)-1));
bnout = arrayfun(binfunc,1:n)
bnout = 1×100
69238785 67239960 137363712 536871682 268992520 8454432 83886128 541074432 18690 8397057 270794760 1056898 553648164 134251648 537141252 1589256 35655681 274688 98376 134226688 537935904 6292224 266306 134480002 68435968 301989900 68157824 159391744 268960320 75530248
dec2bin(bnout(1),bin_len)
ans = '000100001000001000000000000001'

Voss
Voss 2022 年 7 月 22 日
bin_len = 30;
num_1 = 4;
% initialize numeric vector of 30 zeros
bnout = zeros(1,bin_len);
% place ones at 4 random indices
bnout(randperm(bin_len,num_1)) = 1;
disp(bnout)
0 0 0 1 0 0 0 0 1 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 1 0 0 0 0 0
% if you want a character (instead of numeric) vector
bnout = char(bnout+'0');
disp(bnout)
000100001000000010000000100000

カテゴリ

Help Center および File ExchangeRandom Number Generation についてさらに検索

タグ

Community Treasure Hunt

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

Start Hunting!

Translated by