0

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

joke
  • 41

2 Answers2

4

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

2

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
Luis Mendo
  • 1,834