乘法矩阵时的TypeError

时间:2013-06-02 17:11:55

标签: python matrix typeerror

我正在尝试将一些矩阵相乘,并且在最后一次乘法(计算C)时不断出现类型错误。所有其他乘法都正确进行,但我收到错误:

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

1 个答案:

答案 0 :(得分:0)

您只有列表但需要矩阵。写:

A1 = matlib.matrix([[1, 0, 0, 0], [0,1,0,0], [0,0,1,0], [0,0,0,1]])
A2 = matlib.matrix(...

用于所有矩阵。