problem in converting normal array to numpy

1

The program organizes is done to organize the rows, based on the value of the third column, I did the program and it worked, but when I use numpy array, it gives the error below. I need to use numpy array because it's part of a larger program that I'm 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

ERROR THAT YOU ARE GIVING:

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
    
asked by anonymous 24.08.2018 / 03:36

1 answer

0

What happens is that y is always an array, whereas the output of the function OrdenaMatriz() is a list of arrays (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 will happen y=a , so now y is a list of arrays and not an array anymore.

Only in the second loop (since we still have c=True ) it starts having OrganizaMatriz(y) , but the function expects an array as an argument and not a list of arrays.

Then 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 function OrderManx (y) should be an array, not a list of arrays. 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]]
    
24.08.2018 / 16:51