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.
Artjom B.
62k26 gold badges136 silver badges236 bronze badges
asked Jun 21, 2013 at 17:23
3 Answers 3
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)
answered Jun 21, 2013 at 17:26
Sign up to request clarification or add additional context in comments.
5 Comments
user2509830
Thanks for the help. After the matrix is created, how can i access values inside the matrix? for instance, is the value in the 2nd row, 3rd column just example_matrix[2][3]?
RussellStewart
essentially, but python uses a 0 to index the first element, so the 2nd row, 3rd column, so it would be example_matrix[1][2]
SethMMorton
@user2237635 That is true for python's lists of lists, but a multidimensional numpy array is indexed like
[x,y]
, not [x][y]
mgilson
Isn't there a
numpy.fill_diagonal
?Daniel
http://docs.scipy.org/doc/numpy/reference/generated/numpy.fill_diagonal.html
New in 1.4.0 and likely a lot faster since the indices are never constructed. Just uses fancy slicing.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)]
answered Jun 21, 2013 at 17:41
Comments
Here is a simple python line to create a 2D matrix - 100X100:
yourmatrix = [[0 for x in xrange(100)] for x in xrange(100)]
Saullo G. P. Castro
59.4k28 gold badges191 silver badges244 bronze badges
answered Jun 21, 2013 at 17:34
Comments
lang-py
http://wiki.scipy.org/Cookbook/BuildingArrays