Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generate a matrix without 0 values in a random way

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]
like image 419
adamista Avatar asked Apr 02 '19 10:04

adamista


Video Answer


2 Answers

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

like image 153
Marce Avatar answered Sep 25 '22 22:09

Marce


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]]
like image 43
jdehesa Avatar answered Sep 26 '22 22:09

jdehesa