How to generate a random number of n bits length?
Show older comments
Let's say a function takes input n as the bit length and outputs a random number. For example, for n = 4, the output range is [0 - 15] which also includes the range for n = 3 i.e. [0 - 7]. The function should generate the number in the range [8 - 15] and not in the range [0 - 15]. How to do this and how to generalize it for any n?
3 Comments
KALYAN ACHARJYA
on 6 Sep 2018
Edited: KALYAN ACHARJYA
on 6 Sep 2018
The function should generate the number in the range [8 - 15] and not in the range [0 - 15]. How to do this and how to generalize it for any n?
Can you clarify this statement? if n=3 then ??
What I am getting you want three-bit representation(when n=3) in the range [8 - 15]??
Mohsin Shah
on 6 Sep 2018
KALYAN ACHARJYA
on 6 Sep 2018
Edited: KALYAN ACHARJYA
on 6 Sep 2018
@Mohsin Check my answer, as per your requirement? If any modification required, let me know.
Accepted Answer
More Answers (1)
KALYAN ACHARJYA
on 6 Sep 2018
Edited: KALYAN ACHARJYA
on 6 Sep 2018
function bit_result=rand_bits(n)
result=randi([2^(n-1), 2^n]);
bit_result=de2bi(result,n)
end
3 Comments
Mohsin Shah
on 6 Sep 2018
KALYAN ACHARJYA
on 6 Sep 2018
Edited: KALYAN ACHARJYA
on 6 Sep 2018
@Mohsin I have edited the answer, can you verify it?
Mohsin Shah
on 6 Sep 2018
Categories
Find more on Random Number Generation in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!