Reputation: 215
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]
Upvotes: 6
Views: 2715
Reputation: 559
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))
Upvotes: 2
Reputation: 1640
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.
Upvotes: 0
Reputation: 59731
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]]
Upvotes: 7
Reputation: 76
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).
Upvotes: 6