在Numpy中创建矩阵?

2024-09-30 01:24:27 发布

您现在位置:Python中文网/ 问答频道 /正文

我尝试过不同的方法,但我不明白为什么我不能在numpy中创建矩阵。在

当我调用以下命令时,我得到一个“TypeError:new()接受2到4个位置参数,但给出了5个”错误:

def createGST(dictionary):
    x = int(dictionary['x'])
    y = int(dictionary['y'])
    z = int(dictionary['z'])
    matrix = np.matrix( (str(1),str(0),str(0),str(x)),(str(0),str(1),str(0),str(y)),(str(0),str(0),str(1),str(z)),(str(0),str(0),str(0),str(1)) )
    return matrix

即使没有str()的类型转换,它也无法工作。 我使用的是python3.4。在


Tags: 方法命令numpynew参数dictionarydef错误
2条回答

关于4个参数的错误消息,请查看np.matrix代码,说明原因:

class matrix(N.ndarray):
    def __new__(subtype, data, dtype=None, copy=True):
    ....

np.matrix([...],...)创建一个matrix类的对象。因此它将该类称为__new__。通常,对象创建调用__init__,但是这里一定有一些细微差别,需要使用底层的__new__。在任何情况下,您都可以看到错误消息中提到的4个参数。第一种是自动的。所以加上四个元组就等于5。在

如果你错过了你的MATLAB许可证,看看Octave。它使用相同的语法。不过,欢迎使用Python和numpy。在

np.matrix可以使事物看起来更像MATLAB,但更像旧版本(例如3.5)。你被限制在2d。一般来说,基本的np.array更有用。在

错误信息中的答案是正确的。您将向np.matrix传递五个参数:

matrix = np.matrix((str(1), str(0), str(0), str(x)),
                   (str(0), str(1), str(0), str(y)),
                   (str(0), str(0), str(1), str(z)),
                   (str(0), str(0), str(0), str(1)))

np.matrix不接受五个参数。这就是你要做的:

^{pr2}$

注意额外的括号。在

相关问题 更多 >

    热门问题