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

17 Ansichten (letzte 30 Tage)
Camie
Camie am 22 Jul. 2022
Beantwortet: Voss am 22 Jul. 2022
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

Antworten (2)

Mohammad Sami
Mohammad Sami am 22 Jul. 2022
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 am 22 Jul. 2022
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

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!

Translated by