【问题标题】:TypeError when multiplying matrices矩阵相乘时出现类型错误
【发布时间】:2013-06-02 17:11:55
【问题描述】:

我正在尝试将一些矩阵相乘,但我不断收到最后一次乘法(计算 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

【问题讨论】:

  • 请务必包含完整的回溯,这样我们就不必猜测错误发生在您的代码中的哪个位置。
  • 如果没有实现加法/乘法的代码,我们应该如何回答?我的猜测是,在某些时候你正在用单个值替换一个列表,或者你有一个列表而不是一个整数。
  • 对不起,我以为 matlib 是一个标准库。该功能已提供。

标签: python matrix typeerror


【解决方案1】:

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

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

适用于所有矩阵。

【讨论】:

    猜你喜欢
    • 2015-06-20
    • 1970-01-01
    • 2021-04-19
    • 1970-01-01
    • 2017-02-17
    • 2021-12-25
    • 1970-01-01
    • 2016-06-02
    • 1970-01-01
    相关资源
    最近更新 更多