1

I wrote a code to populate a matrix with 0 or 1 randomly. But it ended in 4-5 lines. I want it to be in 1 line.

pop_size = (8,10)
initial_pop = np.empty((pop_size))
for i in range(pop_size[0]):
     for j in range(pop_size[1]):
          initial_pop[i][j] = rd.randint(0,1)
John Coleman
  • 51,337
  • 7
  • 54
  • 119
Kivtas
  • 27
  • 1
  • 6

5 Answers5

1

I understand you are using NumPy. If so, then the answer is:

np.random.randint(2, size=pop_size)

Here is NumPy docs article on this routine: LINK. Numpy is well-documented, next time try checking the docs yourself.

edit: the argument should be 2, not 1

mgradowski
  • 71
  • 5
  • 3
    Having `1` won't work. Needs to be `2` for the first argument. Otherwise you'll get `0`s everywhere. – hqkhan Jan 07 '19 at 18:13
  • @hqkhan you're right. It's inconsistent with python's `random.randint` whose upper bound is inclusive. – mgradowski Jan 07 '19 at 19:02
1

In standard Python, try:

from random import randint
x = [[randint(0,1) for _ in range(8)] for _ in range(10)]
fraczles
  • 81
  • 3
1

Use numpy's randint method

matrix = np.random.randint(2, size=pop_size)
Employee
  • 3,109
  • 5
  • 31
  • 50
0

Check out the answer on : Simple way to create matrix of random numbers

you can easily populate a matrix using numPy.

e.g:

3x3 matrix :

import numpy as np
my_matrix = np.random.randint(2,size=3)

output = ([[0,1,0],
          [0,0,1],
          [1,0,1]])

documentation: https://docs.scipy.org/doc/numpy/reference/generated/numpy.random.randint.html?highlight=randint#numpy.random.randint

Brandon Bailey
  • 781
  • 6
  • 12
0

If you want to have only 1 or 0 in your array you can do so by following.

    import numpy as np
    np.zeros(2,2) #it will create [2,2] matrix with all zeros
    np.ones(2,2)  #it will create [2,2] matrix with all ones