python - 未正确附加矩阵

标签 python python-3.x numpy matrix

我的代码是供用户创建一个应用于起始状态的自定义矩阵。因为我希望它能够生成用户希望的任何方阵,所以我必须做一些时髦的事情。我的基本方法是让用户输入不同的元素,这些元素都放在一个列表中。根据列表中元素的位置,将它们放入不同的行中。我使用 numpy.append() 执行此操作。但是,它给出了错误

Traceback (most recent call last):
  File "/home/physicsnerd/Documents/Quantum-Computer-Simulator/tests.py", line 39, in <module>
    customop(qstat)
  File "/home/physicsnerd/Documents/Quantum-Computer-Simulator/tests.py", line 21, in customop
    np.append(matrix,current_row,axis=0)
  File "/usr/lib/python3/dist-packages/numpy/lib/function_base.py", line 4575, in append
    return concatenate((arr, values), axis=axis)
ValueError: all the input arrays must have same number of dimensions

响应我的 .append() 行。我做错了什么?

要重现此特定代码案例中的错误,请键入“2”、“enter”、“0”、“enter”、“1”、“enter”、“1”、“enter”、“0”、“enter”,尽管这似乎中断了最后四个中的任何数字。另一个注意事项 - print(current_row) 行供调试引用。与 print(matrix) 行相同。

代码

import numpy as np
import math

def customop(qstat):
    dimensions = float(input("What are the dimensions of your (square) matrix? Please input a single number: "))
    iterator = 1
    iterator_2 = 1
    elements = []
    while iterator <= dimensions:
        while iterator_2 <= dimensions:
            elements.append(float(input("Matrix element at "+str(iterator)+","+str(iterator_2)+": ")))
            iterator_2+=1
        iterator_2 = 1
        iterator+=1
    matrix = np.matrix([])
    element_places = list(range(len(elements)))
    current_row = []
    for i in element_places:
        print(i%dimensions)
        if i%dimensions == 0 and i > 0:#does this work? column vs row, elements, etc
            np.append(matrix,current_row,axis=0)
            current_row = []
            current_row.append(elements[i])
        elif i == 0:
            current_row.append(elements[i])
            print(current_row)
        else:
            current_row.append(elements[i])
            print(current_row)
    if np.array_equal(np.dot(matrix, matrix.conj().T), np.identity(2)) == True:
        print(matrix)
        return np.dot(matrix, qstat)
    else:
        print(matrix)
        print("matrix not unitary, pretending no gate was applied")
        return qstat

qstat = np.matrix([[0],[1]])
customop(qstat)

最佳答案

鉴于您在上面指定的输入(大小 2 和元素 0、1、1、0),错误来自于您试图将一行 2 元素附加到空矩阵。如果变成 np.array,您的(空)矩阵的形状为 (1, 0),而 current_row 的形状为 (2, )。

正如上面提到的 DYZ,你已经知道你的矩阵维度,所以你可以将你的输入重新整形为一个方阵,如下所示

np.matrix(elements).reshape((int(dimensions), int(dimensions)))

由于您要求的元素顺序与 reshape 函数的默认工作方式一致,因此您无需添加更多内容。请注意,我必须转换为上面的整数,因为您将尺寸解析为 float 。

如此简化,您的代码将如下所示:

# matrix.py

import numpy as np
import math

def customop(qstat):
    dimensions = int(input("What are the dimensions of your (square) matrix? Please input a single number: "))
    iterator = 1
    iterator_2 = 1
    elements = []
    while iterator <= dimensions:
        while iterator_2 <= dimensions:
            elements.append(float(input("Matrix element at "+str(iterator)+","+str(iterator_2)+": ")))
            iterator_2+=1
        iterator_2 = 1
        iterator+=1
    matrix = np.matrix(elements).reshape(dimensions, dimensions)
    if np.array_equal(np.dot(matrix, matrix.conj().T), np.identity(2)) == True:
        print(matrix)
        return np.dot(matrix, qstat)
    else:
        print(matrix)
        print("matrix not unitary, pretending no gate was applied")
        return qstat

qstat = np.matrix([[0],[1]])
customop(qstat)

示例输出

$ python3 matrix.py
What are the dimensions of your (square) matrix? Please input a single number: 3
Matrix element at 1,1: 1
Matrix element at 1,2: 2
Matrix element at 1,3: 3
Matrix element at 2,1: 1
Matrix element at 2,2: 2
Matrix element at 2,3: 3
Matrix element at 3,1: 1
Matrix element at 3,2: 2
Matrix element at 3,3: 3
[[ 1.  2.  3.]
 [ 1.  2.  3.]
 [ 1.  2.  3.]]

其他优化

如果您知道您的矩阵是正方形的,那么您可以推断出维度将是输入元素数量的平方根

dimensions = math.sqrt(len(elements))

请注意,这可能会使错误处理复杂化并影响用户体验。

旁注

可以用来查看正在发生的事情的有用工具是 ipdb。我掉线了

import ipdb; ipdb.set_trace()

就在您原来的 np.append 行之前,这有助于我突出显示您的错误。

关于python - 未正确附加矩阵,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45724806/

相关文章:

c++ - 将递归 Python 列表生成器转换为 C++

python - 二维输入的 Keras 模型

python - 使用循环从列表中弹出项目

python - swig c++ 到 python (with numpy) : error: use of undeclared identifier 'import_array'

python - 在 python 中使用子进程检查 ping 是否成功

python - 更新继承的django模型字段属性?

python-3.x - 如何将文件传递给docker镜像?

python - 按除数查找开关

python - 如何在 Python 中实现 Softmax 函数

Python:计算 3D 网格的梯度