Matrix scheduling in Python

Asked

Viewed 1,878 times

1

I have problems trying to scale a matrix 5x5. First I made a null line go to the last line of the matrix (it worked out), then I tried to make a line that had the highest index be below that which had a lower index, but on the line:

if pivos_indices[i] > pivos_indices[linha_aux] and linha_aux < 5 and i < 5:

of the code, the compiler warns that the list index is out of range, but I don’t know why (that’s the problem). Below follows the code:

import numpy as np

def buscar_pivo(L):
    if (np.nonzero(L)[0]).size == 0:
        return -1
    else:
        return np.nonzero(L)[1][0]

def encontrar_pivos_indices(mat):
    pivos = []
    for i in range(5):
        pivos.append(buscar_pivo(np.array(mat[i])))
    return pivos

mat = np.matrix([[0,5,2,7,8],[8,10,4,14,16],[0,0,0,0,0],[2,6,10,16,22],[3,5,8,9,15]]).astype(float)
print("Matriz original:\n",mat,"\n")

pivos_indices = encontrar_pivos_indices(mat)

linha_aux = 0
for i in range(5):
    linha_aux = linha_aux + 1
    if pivos_indices[i] == -1 and linha_aux < 5 and i < 5:
        m = mat.tolist()
        (m[i],m[linha_aux]) = (m[linha_aux],m[i])
        mat = np.matrix(m)
        pivos_indices = encontrar_pivos_indices(mat)

print(mat,"\n")

linha_aux = 0
for i in range(5): 
    linha_aux = linha_aux + 1
    if pivos_indices[i] > pivos_indices[linha_aux] and linha_aux < 5 and i < 5:
        m = mat.tolist()
        (m[i],m[linha_aux]) = (m[linha_aux],m[i])
        mat = np.matrix(m)
        pivos_indices = encontrar_pivos_indices(mat)

print(mat)

1 answer

1


There are five possible indexes in your matrix, ranging from 0 to 4. On the line

for i in range(5):

you execute five iterations, making the value of linha_aux range from 1 to 5. This way, in the last iteration you will try to access an index that does not exist.

To solve the problem, just move to the end of iteration the line incrementing the counter linha_aux:

for i in range(5): 
    if pivos_indices[i] > pivos_indices[linha_aux] and linha_aux < 5 and i < 5:
        m = mat.tolist()
        (m[i],m[linha_aux]) = (m[linha_aux],m[i])
        mat = np.matrix(m)
        pivos_indices = encontrar_pivos_indices(mat)
    linha_aux = linha_aux + 1

Browser other questions tagged

You are not signed in. Login or sign up in order to post.