How to create Random Binary Number with fix amount of 1 and 0?
조회 수: 18 (최근 30일)
이전 댓글 표시
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
댓글 수: 0
답변 (2개)
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)
dec2bin(bnout(1),bin_len)
댓글 수: 0
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)
% if you want a character (instead of numeric) vector
bnout = char(bnout+'0');
disp(bnout)
댓글 수: 0
참고 항목
카테고리
Help Center 및 File Exchange에서 Random Number Generation에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!