43 views (last 30 days)

Guillaume
on 6 Sep 2018

For n = 4 it should generate a number in the range [8-15]

If I understand correctly, you want a 4 bit random number with the MSB always set to 1. That sounds like a strange requirement, probably not thought properly, but this is simply equivalent to generating a 3 bit random number and tacking 1 as the MSB. The generic version of that (generating a n-1 bit number + MSB of 1) is:

n = 4

number = randi([1, 2^(n-1)]) + 2^(n-1) - 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

Sign in to answer this question.

Opportunities for recent engineering grads.

Apply Today
## 3 Comments

## Direct link to this comment

https://www.mathworks.com/matlabcentral/answers/417783-how-to-generate-a-random-number-of-n-bits-length#comment_607155

⋮## Direct link to this comment

https://www.mathworks.com/matlabcentral/answers/417783-how-to-generate-a-random-number-of-n-bits-length#comment_607155

## Direct link to this comment

https://www.mathworks.com/matlabcentral/answers/417783-how-to-generate-a-random-number-of-n-bits-length#comment_607157

⋮## Direct link to this comment

https://www.mathworks.com/matlabcentral/answers/417783-how-to-generate-a-random-number-of-n-bits-length#comment_607157

## Direct link to this comment

https://www.mathworks.com/matlabcentral/answers/417783-how-to-generate-a-random-number-of-n-bits-length#comment_607158

⋮## Direct link to this comment

https://www.mathworks.com/matlabcentral/answers/417783-how-to-generate-a-random-number-of-n-bits-length#comment_607158

Sign in to comment.