5

I am trying to create a matrix in a random way in the intervals [-5,-1] and [1,5]. How can I create a matrix taking into account the intervals (no 0 values) with random values?

I tried to do it with randint of numpy and with piecewise. In the first case it is not posible to indicate 2 intervals and in the second case the random number generated when the value is close to 0 (bigger than -1 and lower than 1) is always the same.

    x=np.random.randint(-5,5,(2,3))
    np.piecewise(x, [x <= 1, x >=-1 ], [np.random.randint(-5,-1), np.random.randint(1,5)])

I would like to have a matrix in this way with no 0 values:

  [-2,-3,-1
    1,-2, 3]
1
  • Are you consider to use random.randrange( ... ) with some additional numpy array option?
    – ElConrado
    Apr 2, 2019 at 10:16

4 Answers 4

6

You can create a random positive matrix and multiply it element wise by a random sign:

np.random.randint(1,6,(2,3))*np.random.choice([-1,1],(2,3))

Keep in mind that this only works if the interval is even around 0, e.g. (-6,6) (0 excluded).

6

One option is to simply "remap" the value 0 to one of the bounds:

import numpy as np

np.random.seed(100)
x = np.random.randint(-5, 5, (4, 8))
x[x == 0] = 5
print(x)
# [[ 3  3 -2  2  2 -5 -1 -3]
#  [ 5 -3 -3 -3 -4 -5  3 -1]
#  [-5  4  1 -3 -1 -4  5 -2]
#  [-1 -1 -2  2 -4 -4  2  2]]

Or you can use np.random.choice:

import numpy as np

np.random.seed(100)
np.random.choice(list(range(-5, 0)) + list(range(1, 6)), size=(4, 8))
print(x)
# [[ 3  3 -2  2  2 -5 -1 -3]
#  [ 5 -3 -3 -3 -4 -5  3 -1]
#  [-5  1 -3 -1 -4  5 -2 -1]
#  [-1 -2  2 -4 -4  2  2 -5]]
3
  • Keep in mind, that the first solution makes the distribution non-uniform!
    – fulaphex
    Apr 2, 2019 at 10:17
  • @fulaphex Does it? How so? Do not all 10 values have all the same probability of being chosen?
    – jdehesa
    Apr 2, 2019 at 10:18
  • 1
    Sorry, I misread the bounds on the randint function. But I think there is still an error, I think it should be x = np.random.randint(-5, 5, (4, 8)). From the docs, the high value is one above the largest integer to be drawn.
    – fulaphex
    Apr 2, 2019 at 10:23
2
np.random.choice(list(range(-5,0))+list(range(1,6)),(5,5))

or

a = list(range(-5,6))
a.remove(0)
np.random.choice(a,(5,5))
0
import numpy as np
a = np.arange(-5,6)
np.random.choice(list(numpy.select([a != 0, a == 0], [a, -1])),(5,5))

It's the other way where you can define your own condition of list. You can ommit whatever number from array 'a' you want by editing condition. In above on numbers equal to zero return -1 and for numbers non equal to zero return same number.

1
  • Thanks, but this only create a random number between intervals but I need a matrix
    – adamista
    Apr 2, 2019 at 10:22

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.