problem in converting normal matrix to numpy

Asked

Viewed 110 times

1

The program organizes is made to organize the lines, based on the value of the third column, I did the program and it worked, but when I use numpy matrix, gives the error below. i need to use numpy array because it is part of a larger program that I am using numpy.

import numpy as np

y = np.matrix([[-1,1,4],[2,-2,7],[10,7,1]])

c = True

def OrdenaMatriz(y):
    matriz = []
    matriz.append(y[0])
    for a in range(2):
        if y[a,2] < y[a+1,2]:
            matriz.insert(a,y[a+1])
        else:
            matriz.append(y[a+1])
    return matriz

while c == True:
    a = OrdenaMatriz(y)
    if a == y:
        c = False
        print(a)
    y = a

MISTAKE YOU ARE MAKING:

DeprecationWarning: elementwise == comparison failed; this will raise an 
error in the future.
  if a == y:
Traceback (most recent call last):
  File "teste.py", line 26, in <module>
    a = OrdenaMatriz(y)
  File "teste.py", line 19, in OrdenaMatriz
    if y[a,2] < y[a+1,2]:
TypeError: list indices must be integers or slices, not tuple
  • Hello @João-Vitor-Degrandi, okay. I can try to help, but what would a normal Matrix be? It would be a list of lists ?

1 answer

1


What happens is that y is always a matrix, the output of the function OrdenaMatriz() is a list of matrices (vectors). This is:

>>> y = np.matrix([[-1,1,4],[2,-2,7],[10,7,1]])
>>> y
matrix([[-1,  1,  4],
        [ 2, -2,  7],
        [10,  7,  1]])

>>> a = OrdenaMatriz(y)
>>> a
[matrix([[ 2, -2,  7]]),
 matrix([[-1,  1,  4]]),
 matrix([[10,  7,  1]])]

At the end of the first loop it will happen y=a, So now y is a list of matrices and no longer a matrix.

Only on the second loop (since we still have c=True) he starts by having to apply OrganizaMatriz(y), but the function expects a matrix as argument and not a list of matrices.

So you have to do the following:

>>> a = OrdenaMatriz(y)
>>> while c == True:
...     if a == y:
...         c = False
...         print(a)
...     y = a
[matrix([[ 2, -2,  7]]), matrix([[-1,  1,  4]]), matrix([[10,  7,  1]])]

NOTE [EDITED]:

I believe that the output of the Sort(y) function should be a matrix and not a list of matrices. So I suggest this modification:

def OrdenaMatriz(y):
    matriz = []
    matriz.append(y[0])
    for a in range(2):
        if y[a,2] < y[a+1,2]:
            matriz.insert(a,y[a+1])
        else:
            matriz.append(y[a+1])
    return np.asmatrix(np.asarray(matriz))

So you can apply your original loop by modifying only the condition of if:

c=True
>>> while c == True:
...     a = OrdenaMatriz(y)
...     if (a==y).all():
...         c = False
...         print(a)
...     y = a
...
[[ 2 -2  7]
 [-1  1  4]
 [10  7  1]]

Browser other questions tagged

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