Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

generating odd random numbers using Matlab

Tags:

matlab

I need some help on how to generate odd random numbers using Matlab. How do you generate odd random numbers within a given interval, say between 1 and 100?

like image 543
user1727549 Avatar asked May 19 '26 04:05

user1727549


1 Answers

Well, if I could generate EVEN random numbers within an interval, then I'd just add 1. :)

That is not as silly as it sounds.

Can you generate random integers? If you could, why not multiply by 2? Then you would have EVEN random integers. See above for what to do next.

There are tools in MATLAB to generate random integers in an interval. If not, then you could write your own trivially enough. For example, what does this do:

r = 1 + 2*floor(rand(N,1)*50);

Or this:

r = 1 + 2*randi([0 49], N,1);

Note that Rody edited this answer, but made a mistake when he did so when using randi. I've corrected the problem. Note that randi intentionally goes up to only 49 in its sampling as I have changed it. That works because 2*49 + 1 = 99.

So how about in the rand case? Why have I multiplied by 50 there, and not 49? This is taken from the doc for rand:

"r = rand(n) returns an n-by-n matrix containing pseudorandom values drawn from the standard uniform distribution on the open interval (0,1)."

So rand NEVER generates an exact 1. It can generate a number slightly smaller than 1, but never 1. So when I multiply by 50, this results in a number that is never exactly 50, but only potentially slightly less than 50. The floor then generates all integers between 0 and 49, with essentially equal probability. I suppose someone will point out that since 0 is never a possible result from rand, that the integer 0 will be under-sampled by this expression by an amount of the order of eps. If you will generate that many samples that you can see this extent of undersampling, then you will need a bigger, faster computer to do your work. :)


Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!