0

I'm trying to generate a random integer in the range of -2 and 5 using round and rand functions. I'm able to generate a random integer however it always returns a negative value and a zero.

round(rand(1)*-5)
PRCube
  • 566
  • 2
  • 6
  • 19

2 Answers2

0

Use randi

r = randi([-2 5],1)

rand

And if you want to do this only using rand and round Try this: r = round(rand(1)*7 - 2);

Tony Tannous
  • 14,154
  • 10
  • 50
  • 86
0

heres also a possible way of doing it:

% generate 1000 random integers between -2 and 5
R = ceil(rand(1000,1)*8)-3;

% display MIN / MAX
disp(min(R));
disp(max(R));
dcts
  • 1,479
  • 15
  • 34
  • Note that this works because @thomas is using `ceil`, and therefore has to increase the factor by 1 (so is using 8 instead of 7). This works because rand() never generates a true 0 or 1. Otherwise if true 0 is generated, this formula will sometimes (with low probability) generate the number -3. –  Oct 27 '16 at 08:46