Generate a random integer between -2 and 1 inclusive

2k Views Asked by At

How can one generate a random integer between -2 and 1 inclusive? I know if I take rand*(b-a)+a I would get random real number between a and b Thanks

2

There are 2 best solutions below

0
On

$$\lfloor4\operatorname{rand}()\rfloor-2$$

0
On

You can use randi, which generates integers between 1 and the specified input argument:

randi(4)-3

If you don't have the randi function (it is included in newest versions of Matlab), you could use rand with ceil:

ceil(rand*4)-3