Reputation: 93
I am trying to create a 100 by 100 matrix that will be populated with 1's and -1's(at random), and the diagonal of the matrix should be all zeros.
I am new to python and numpy.
Upvotes: 1
Views: 12066
Reputation: 414
Here is a simple python line to create a 2D matrix - 100X100:
yourmatrix = [[0 for x in xrange(100)] for x in xrange(100)]
Upvotes: 0
Reputation: 58995
To create the matrix with ones:
a = numpy.ones( (100,100) )
To create the random matrix:
a = numpy.random.random( (100,100) ) # by default between zero and one
To set all the diagonals to zero:
numpy.fill_diagonal(a, 0)
Upvotes: 3
Reputation: 3131
As an alternative, just using list comprehension and random:
from random import randint
x = [1,-1]
my_matrix = [[x[randint(0,1)] if i!=j else 0 for i in range(100)] for j in range(100)]
This will give you the random choice between -1 and 1 with 0 for the diagonal. You can embed this in a function to give you a matrix of NxN size as follows:
from random import randint
def make_matrix(n):
x = [-1,1]
return [[x[randint(0,1)] if i!=j else 0 for i in range(n)] for j in range(n)]
Upvotes: 0