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)
2
  • "returns a negative value and a zero". That's because you're multiplying a number between 0 and 1 by a negative number. The output will always be negative. Commented Oct 27, 2016 at 3:11
  • what should I do? Commented Oct 27, 2016 at 3:13

2 Answers 2

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);

Sign up to request clarification or add additional context in comments.

Comments

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));

1 Comment

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.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.