简体   繁体   English

将法线矩阵转换为numpy

[英]Converting normal matrix to numpy

The purpose of this code is to arrange the lines, using the third column as a parameter. 该代码的目的是使用第三列作为参数来排列行。 If I use normal matrix, the program works just fine, but I need to use numpy, because it's part of a bigger program. 如果我使用普通矩阵,则该程序可以正常运行,但是我需要使用numpy,因为它是更大程序的一部分。

The desired output is : [[2,-2,7],[-1,1,4],[10,7,1]] 所需的输出是:[[2,-2,7],[-1,1,4],[10,7,1]]

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

The following error is showing: 显示以下错误:

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

I'll try to explain your errors and warning. 我将尽力解释您的错误和警告。

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

could just as well be 可能也是

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

You don't, especially as a beginner, need to use np.matrix . 您尤其是初学者,不需要使用np.matrix np.array() produces the regular numpy array object. np.array()产生常规的numpy数组对象。 Using np.matrix is discouraged, since it doesn't add anything special now. 不建议使用np.matrix ,因为它现在不添加任何特殊内容。

a = OrdenaMatriz(y) produces a Python list. a = OrdenaMatriz(y)生成一个Python列表。 You start with [] , and either insert or append values, so the result is still a list. 您从[]开始,然后插入或附加值,因此结果仍然是列表。

It's the 这是

a == y

that produces the DeprecationWarning . 产生DeprecationWarning It's the result of comparing a list with a numpy array. 这是将列表与numpy数组进行比较的结果。

Then you y=a . 然后,您y=a Now y is a list, not the original array (or matrix). 现在y是一个列表,而不是原始数组(或矩阵)。 So on the next loop, OrdenaMatriz is called with a list. 因此,在下一个循环中,使用列表调用OrdenaMatriz That's when 那个时候

y[a,2] < y[a+1,2]

raise the TypeError. 引发TypeError。 That indexing is ok for array/matrix, but not for list. 对于数组/矩阵,该索引是可以的,但对于列表,则不能。

So if you stick with this code, or something similar, start with an np.array() call, and make sure that OrdenaMatriz returns an array, not a list. 因此,如果您坚持使用此代码或类似的代码,请从np.array()调用开始,并确保OrdenaMatriz返回数组,而不是列表。

"The purpose of this code is to arrange the lines, using the third column as a parameter.": “此代码的目的是使用第三列作为参数来排列行。”:

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

Like this? 像这样?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM