MATLAB: Random Number Generator, lower numbers have higher chance

MATLABrandomrandom intervalrandom number generator

Hi. I am trying to create a script for generating a random number, with lower numbers having a higher chance of being picked.
This will be in the range of 1 to 20
The percent chance is going to be based on (0.5)^n
So the chance of getting a 1 is 50%, the chance of getting a 2 is 25%, 3 is 12.5% and so on….
I am having trouble getting started with this. I'm not even sure if there is a way. You don't have to write this out, I would just like someone to help me get started or send me in the right direction.

Best Answer

min(ceil(-log2(rand)),20)