# Python matrix

0 218

In Python we can create matrix using a double for loop, or we can just use the Numpy library.

In this lesson we will create arrays using iterative instructions, later we will see the use of Numpy.

## Python matrix – first exercise

In this first exercise we use a double for loop to create arrays with random numbers.

In particular, we will create a 3 x 3 matrix, but then we will generalize the algorithm by creating matrices of custom size.

First of all, since I have to generate random numbers, I import the random module and in particular randint.

After, I create an empty list and with the first for loop I go through all the lines. For each line it uses another for loop and I generate a list of 3 random numbers. At the end of the innermost loop I use Python’s append method to append the generated list to the starting matrix.

Here is a possible solution to create matrix in Python:

``````
from random import randint

matrix = []

for i in range(3):
n = []
for j in range(3):
number = randint(1,100)
n.insert(i,number)

matrix.append(n)

print(matrix)

``````

We can populate an array with a while loop, but that’s not the optimal solution. In fact, remember that when we know exactly how many times a loop must be executed, we use the for. The while is used instead when I need to satisfy a condition.

``````
from random import randint
matrix = []
i=0
while i < 3:
j = 0
n = []
while j < 3:
number = randint(1,100)
n.insert(i,number)
j = j+1
matrix.append(n)
i = i+1
print(matrix)
``````

Let’s now create a function in Python to generate a matrix:

``````
from random import randint

def matrix(x,y):
matrix = []

for i in range(x):
n = []

for j in range(y):
number = randint(1,100)
n.insert(i,number)

matrix.append(n)

return matrix

print(matrix(3,3))

``````

In this way we can generate matrices of any size.

## Python matrix – second exercise

We ask the user as input for the size of the matrix to be generated.

``````
from random import randint

def matrix(x,y):
matrix = []

for i in range(x):
n = []

for j in range(y):
number = randint(1,100)
n.insert(i,number)

matrix.append(n)

return matrix

x = int(input('enter the x dimension of the matrix '))
y = int(input('enter the y dimension of the matrix '))

print(matrix(x,y))

``````

Let’s try the code just generated in the compiler below:

In this Python lesson we developed matrix by simply using a double for loop. In the next few lessons we will study Numpy.