필터 지우기
필터 지우기

How to generate a a restricted binary number

조회 수: 1 (최근 30일)
Mohsen
Mohsen 2018년 12월 5일
댓글: Mohsen 2018년 12월 6일
Dear friends
I would like to generate a random number include 24 bits 4 bits of 1 and 20 bits of 0. Can you help me?
Best Regards
Mohsen

채택된 답변

Jan
Jan 2018년 12월 5일
편집: Jan 2018년 12월 5일
What exactly is a "number include 24 bits"?
This sets 4 elements to 1 and 20 to 0:
v = zeros(1, 24);
v(randperm(24, 4)) = 1;
What is the wanted output?
result = bin2dec('0' + v)
% or
result = v * power(2, 0:23).'
Instead of creating the sum using the dot product, you can use the indices replied by randperm directly:
result = sum(2 .^ (randperm(24, 4) - 1));
I hope this was not a homework question. Otherwise it will be hard for you to submit your own solution now. But you participate in this forum for 6 years now, such that I assume that you are not in the learning phase anymore.

추가 답변 (1개)

Mohsen
Mohsen 2018년 12월 5일
편집: Mohsen 2018년 12월 5일
Exuce me,
There is a problem. In fact, i have a optimization algorithm and the input dimention and max and min. must be determined.
a posible state can be:
[0 1 0 1 1 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0]
or
[0 0 0 1 1 0 0 0 0 0 0 1 0 0 0 0 0 0 0 1 0 0 0 0]
or...
there are four swing "1"s in this vector and total states is equal 10626(=). the vector length is 24. How do i define number dimention, max and min to derive this array?
  댓글 수: 2
Jan
Jan 2018년 12월 6일
편집: Jan 2018년 12월 6일
I do not understand what "number dimension, max and min" means. Maximum and minimum of what? My answer includes a method to create random vectors already:
v = zeros(1, 24);
v(randperm(24, 4)) = 1;
Do you now want to create all these vectors? Then:
M = nchoosek(1:24, 4);
for k = 1:size(M, 1)
v = zeros(1, 24);
v(M(k, :)) = 1;
...
end
Mohsen
Mohsen 2018년 12월 6일
I get a new idea by your post.
Thank you very much

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

카테고리

Help CenterFile Exchange에서 Logical에 대해 자세히 알아보기

태그

제품

Community Treasure Hunt

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

Start Hunting!

Translated by