【发布时间】:2017-08-17 00:18:48
【问题描述】:
我的代码是让用户创建一个应用于起始状态的自定义矩阵。因为我希望它能够生成用户希望的任何方阵,所以我必须做一些时髦的事情。我的基本方法是让用户输入不同的元素,这些元素都放在一个列表中。根据列表中元素的位置,将它们放入不同的行中。我使用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”,输入,“0”,输入,“1”,输入,“1”,输入,“0”,输入,尽管这似乎中断了最后四个中的任何数字。另一个注意事项 - 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)
【问题讨论】:
-
请附上完整的错误信息。
-
@DYZ 我编辑这样做。
-
你现在提前
matrix的尺寸,不是吗?为什么不创建整个完整的矩阵广告,只需将elements[i]存储到正确的位置,而不需要任何appends? -
@DYZ 不,不一定-我只是在特定情况下(2x2 矩阵)进行测试。我希望代码可用于任何维度的矩阵,只要它是正方形的。
-
你没有
len(elements)行和列吗?还是dimensions?
标签: python python-3.x numpy matrix