Python sympy中while循环中的行未添加到矩阵
该程序的目的是构建一个3x3矩阵,然后减少额外的行,但由于某种原因,在while循环中将第二行添加到M之后,它将用新行替换它,而不是添加第三行,然后减少额外的(很可能是3)向量。代码如下:Python sympy中while循环中的行未添加到矩阵,python,matrix,sympy,Python,Matrix,Sympy,该程序的目的是构建一个3x3矩阵,然后减少额外的行,但由于某种原因,在while循环中将第二行添加到M之后,它将用新行替换它,而不是添加第三行,然后减少额外的(很可能是3)向量。代码如下: from sympy import * init_printing(use_unicode= True) A = [] def reduceOneRow(M): k = 0 for i in range(k,min(M.shape)-1): if M[i,i]!=0 or i
from sympy import *
init_printing(use_unicode= True)
A = []
def reduceOneRow(M):
k = 0
for i in range(k,min(M.shape)-1):
if M[i,i]!=0 or i ==2:
for j in range(k,min(M.shape)-1):
T = Matrix([M.row(j+1)-(M[j+1,i]/M[i,i])*M.row(i)])
A.append(M[j+1]/M[i,i])
M.row_del(j+1)
M = M.row_insert(j+1,T)
k = k+1
else:
i = i+1
return M
# M = Matrix([[1,1,1],[1,4,7],[3,2,5]])
# reduceOneRow(M)
# A
#The following block of code generates a list of monomials, but not in reverse
#lexicagraphical order. This can be fixed later. Ultimately, I'd like to
#make it it's own function
sigma = symbols('x1:4')
D = [1]
for d in D:
for s in sigma:
if s*d not in D:
D.append(s*d)
if len(D) > 20:
break
# print(D)
# print(D[9].subs([('x1',4),('x2',2),('x3',3)]))
#We begin with the set up described in C1
P = [(1,2,3),(4,5,6),(7,8,9)]
G = []
Q = []
S = []
L = [1]
M = Matrix([])
#Here we being step C2.
while L != []:#what follows this while statement is the loop C2-C5 and back
t = L[0]
L.remove(L[0])
K = Matrix([]) #K is a kind of bucket matrix
if t==1: #this block generates the firs line in M. It had to be separate
for j in range(len(P)):#because of the way sympy works. 1 is int, rather
K = K.col_insert(j,Matrix([1])) #than a symbol
else: #here we generate all other rows of M, using K for the name of the rows
for p in P:
K = K.col_insert(0,Matrix([t.subs([(sigma[0],p[0]),(sigma[1],p[1]),(sigma[2],p[2])])]))
# K = K.col_insert(i,Matrix([t.subs([(sigma[0],p[0]),(sigma[1],p[1]),(sigma[2],p[2])]))
M = M.row_insert(min(M.shape)+1,K) #K gets added to M
M
A = []
reduceOneRow(M)#row reduces M and produces the ai in C3
sum = 0
for n in range(len(A)):
sum = sum + A[n]*S[n]
V = M.row(-1)
if V == zeros(1,len(V)):
G.append(t - sum)
M.row_del(-1)
else:
S.append(t-sum)
Q.append(t)
for i in range(1,4):
#if not t*D[i] == Q[0]:
L.append(t*D[i])
L
print('G =',' ',G,' ','Q =',Q)
我知道了。我把'reduceRowOne(M)'改为'M=reduceRowOne'。啊
谢谢所有看过这个的人 您需要逐行测试代码,以确保它按照您的预期运行。虽然我对sympy.Matrix类不太熟悉,但您可能没有做任何高级工作。您可以添加许多显示行,或者在交互式会话中复制这些步骤。