3

Possible Duplicate:
Is there a way in Matlab using the pseudo number generator to generate numbers within a specific range?

I want to get 20 random integer numbers between -10 and 10 and I thought of using the rand function in matlab.

I thought of myltiplying by ten and then finding a way to get only the ones between -10 and 10 and use an iteration for each of the other numbers that is outside the limits [-10,10] to get a new number inside the limits.

Is there a better, faster way?

Community
  • 1
  • 1
system
  • 81
  • 1
  • 2
  • 4
  • There are lots of similar questions, but I haven't found one that asked for a range of integers. – Jonas Jun 20 '11 at 18:45

2 Answers2

7

Use

randomIntegers = randi([-10,10],[20,1])

to generate a vector of random integers between -10 and 10.

Jonas
  • 74,690
  • 10
  • 137
  • 177
2

Although Jonas' solution is really nice, randi isn't in some of the early versions of MATLAB. I believe all versions have rand. A solution using rand would be:

randomIntergers = floor(a + (b-a+1) .* rand(20,1));

where [a,b] is the range of values you want a distribution over.

If you are use round(a + (b-a)) you will have a nonuniform effect on the values of 'a' and 'b'. This can be confirmed using the hist() function. This is because the domain that maps into 'a' and 'b' is half the size for all other members of the range.

thron of three
  • 521
  • 2
  • 6
  • 19
  • Actually, I wouldn't use this answer. It's not uniform. Try `a = -10; b = 10; x = round(a + (b-a) .* rand(20000,1)); hist(x,1000);` The -10 and 10 case are less likely than the others. – Chris A. Jun 20 '11 at 19:44
  • 4
    This fixes it. `x = floor(a + (b-a+1) .* rand(20,1));` – Chris A. Jun 20 '11 at 19:46
  • hmm, I always thought 'floor(A)' rounded to the nearest integer less than or equal to A, so 'floor(-.9) = -1' but 'floor(.9) = 0'. Whereas round just goes to the nearest integer. It seems intuitively to me that floor will bias data to the left, giving you a new mean around -0.5. – thron of three Jun 21 '11 at 15:36
  • I suggest computing it and then looking at the `hist(x,1000)` of it then convincing yourself why it works. – Chris A. Jun 21 '11 at 16:00
  • wow, I never took the time to look at the histogram when creating random numbers. There is a nonuniform distribution at the edge numbers using round. This makes sense because the domain that maps into -10 and 10 is half the size for all other members of the range. There still is a problem using floor though, as no members of the range will map into the integer 10. (-10 also gets excluded if you try to use `ceil`). Guess the best way is to pick all positive values with a mean above zero, create a random distribution, then subtract the mean to get a zero mean, uniform distribution. – thron of three Jun 21 '11 at 16:23
  • you didn't catch the `(b-a+1)` instead of `(b-a)` in my comment did you? – Chris A. Jun 21 '11 at 16:42