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)
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)
Use randi
r = randi([-2 5],1)
And if you want to do this only using rand and round
Try this: r = round(rand(1)*7 - 2);
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));
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.