Linux (28) Python (13) Raspberry Pi (5) Bugs (3) Install (3) C (2) Brainf**k (1) HTML (1) Maths (1) Sorts (1)

Tuesday, 6 October 2015

Creating a matrix with python and numpy.

To create a matrix in python we use the library numpy.
Install numpy from that link for the operating system you are running.
If you want to create a 50 by 50 matrix use the following code:

import numpy
matrix = numpy.zeros((50,50))

This creates a matrix that is 50 by 50 and full of zeros.
If you want to fill this random 0's or 1's use this for loop

import numpy
import random

matrix = numpy.zeros((50,50))   #Create a 50 by 50 matrix full of zeros
#Fill matrix with random data
for row in range(0,49):   #Loop used for the row
    for column in range(0,49):   #Loop used  for the column
        matrix[int(row),(column)] = random.randint(0,1)    

print(matrix)    #Print it out to check its worked