在 Numpy 中创建矩阵?

Creating matrices in Numpy?

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

我在调用时收到 "TypeError: new() takes from 2 to 4 positional arguments but 5 were given" 错误:

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() 进行类型转换,它也不起作用。 我正在使用 python 3.4.

错误消息中的答案是正确的。您将五个参数传递给 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 不带五个参数。这就是你想要做的:

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))))

注意额外的括号。

关于4个参数的错误信息,看一下np.matrix代码就知道原因了:

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

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

如果您缺少 MATLAB 许可证,请查看 Octave。它采用大部分相同的语法。不过,欢迎使用 Python 和 numpy。

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