1

I'm new to matlab and trying to learn how to simulate random numbers.

Is there a simple way to create a 10x20 array filled with random numbers from the uniform (-1,1) distribution.

I've seen the rand function, but I'm not sure how to change the uniform (0,1) distribution to (-1,1).

Mikhail_Sam
  • 10,602
  • 11
  • 66
  • 102
yalpsid eman
  • 3,064
  • 6
  • 45
  • 71
  • 1
    Well, you could multiply the result by two and subtract one from it, although that would give you less randomness. – Majora320 Sep 19 '17 at 01:35
  • @Majora320 Why would it give less randomness? That is the accepted method to create the distribution, right? – ammportal Sep 19 '17 at 05:54
  • 6
    Duplicate of [Matlab, matrix containing random numbers within specified range](https://stackoverflow.com/q/14482951/), some other relevant duplicate targets: [***1***](https://stackoverflow.com/q/5077800/), ‍‍‍‍‍‍ ‍‍ [***2***](https://stackoverflow.com/q/27263762/), ‍‍‍‍‍‍ ‍‍ [***3***](https://stackoverflow.com/q/15411585/), ‍‍‍‍‍‍ ‍‍ and the [***official doc***](https://www.mathworks.com/help/matlab/math/floating-point-numbers-within-specific-range.html) – Sardar Usama Sep 19 '17 at 05:58
  • @ammportal Let's say we have a distribution from 0 to 5: [0 1 2 3 4 5]. Each of these has an equal chance of being selected. If we extend that to 0 to 11, only some will be selected: [**0** 1 **2** 3 **4** 5 **6** 7 **8** 9 **10** 11]. Obviously, a floating point range will have much more than just 6 different values but the same principle applies. – Majora320 Sep 19 '17 at 06:24
  • 1
    @Majora320 Yes, but this is true only for a discrete distribution as in your example. A continuous one does not have this limitation. Although you can't say that all the values between 0 and 1 are generated by MATLAB, the number of values are still sufficient though to have little or no effect on the randomness – ammportal Sep 19 '17 at 06:38
  • @ammportal I suppose it is insignificant in practice, but precision is limited by, well, floating-point precision. – Majora320 Sep 19 '17 at 06:48

2 Answers2

1

We actually CAN just deform interval of (0,1) using different math operations and still get uniform distribution.

So you have to go this way:

result = rand(10,20).*2-1

To check is it really still uniform lets do the next:

res = rand(10000).*2-1;
histogram(res)

As you can see it is still uniform.

enter image description here

There are some tricks about random numbers (actually it's pseudorandom) and you can get the same 'random' results after restart MATLAB. read about this here and here.

Mikhail_Sam
  • 10,602
  • 11
  • 66
  • 102
0

You can use the following formula given in Matlab rand documentation to achieve random numbers between any interval of numbers:

r = a + (b-a).*rand(N,1)

In your case for (-1,1) interval and an array sized (10,20) it should be:

r = -1 + (1+1).*rand(10,20)

References: rand Matlab official documentation