0
我想把一些矩陣放在一起,並且我一直得到最後一個乘法的類型錯誤(計算C)。所有其他的乘法進行正確的,但我得到的錯誤:當乘上矩陣時出現TypeError
Traceback (most recent call last):
File "C:\Python27\Lab2_MatMult_template.py", line 31, in <module>
C = matlib.matmul(A1,B)
File "C:\Python27\lib\site-packages\matlib.py", line 158, in matprod
t = sum([A[i][k] * B[j] for k in range(p)])
TypeError: unsupported operand type(s) for +: 'int' and 'list'
我想我可能沒有正確定義的矩陣B(它是一個列向量),但我似乎無法找出確切原因
# Template for multiplying two matrices
import matlib
import math
# Use help(math) to see what functions
# the math library contains
RShoulderPitch = 0
RElbowRoll = 0
# Matrix A
A1 = [[1, 0, 0, 0], [0,1,0,0], [0,0,1,0], [0,0,0,1]]
A2 = [[-1, 0, 0, 0], [0,0,-1,0], [0,-1,0,100], [0,0,0,1]]
A3 = [[0, -1, 0, 0], [1,0,0,0], [0,0,1,98], [0,0,0,1]]
A4 = [[math.cos(-RShoulderPitch), 0, -math.sin(-RShoulderPitch), 105*math.cos(-RShoulderPitch)], [math.sin(-RShoulderPitch),0,math.cos(-RShoulderPitch),105*math.sin(-RShoulderPitch)], [0,-1,0,15], [0,0,0,1]]
# Matrix B
B = [[0],[0],[0],[2]]
T = matlib.matmul(A3,A4)
T = matlib.matmul(A2,T)
T = matlib.matmul(A1,T)
C = matlib.matmul(B,T)
print('C=')
matlib.matprint(T, format='%8.1f')
def matmul(A, B):
"""
Computes the product of two matrices.
2009.01.16 Revised for matrix or vector B.
"""
m, n = matdim(A)
p, q = matdim(B)
if n!= p:
return None
try:
if iter(B[0]):
q = len(B[0])
except:
q = 1
C = matzero(m, q)
for i in range(m):
for j in range(q):
if q == 1:
t = sum([A[i][k] * B[j] for k in range(p)])
else:
t = sum([A[i][k] * B[k][j] for k in range(p)])
C[i][j] = t
return C
請確保包含完整的回溯,因此我們不必猜測代碼中的錯誤發生位置。 –
如果沒有實現加法/乘法的代碼,我們應該如何回答?我的猜測是,在某些時候你用一個單一的值替換一個列表,或者你有一個列表而不是一個整數。 – Bakuriu
對不起,我認爲matlib是一個標準庫。該功能已提供。 – user2445507