python矩阵乘法代码_纯Python中的矩阵乘法?

I'm trying to multiply two matrices together using pure Python. Input (X1 is a 3x3 and Xt is a 3x2):

X1 = [[1.0016, 0.0, -16.0514],

[0.0, 10000.0, -40000.0],

[-16.0514, -40000.0, 160513.6437]]

Xt = [(1.0, 1.0),

(0.0, 0.25),

(0.0, 0.0625)]

where Xt is the zip transpose of another matrix. Now here is the code:

def matrixmult (A, B):

C = [[0 for row in range(len(A))] for col in range(len(B[0]))]

for i in range(len(A)):

for j in range(len(B[0])):

for k in range(len(B)):

C[i][j] += A[i][k]*B[k][j]

return C

The error that python gives me is this:

IndexError: list index out of range.

Now I'm not sure if Xt is recognised as an matrix and is still a list object, but technically this should work.

解决方案

If you really don't want to use numpy you can do something like this:

def matmult(a,b):

zip_b = zip(*b)

# uncomment next line if python 3 :

# zip_b = list(zip_b)

return [[sum(ele_a*ele_b for ele_a, ele_b in zip(row_a, col_b))

for col_b in zip_b] for row_a in a]

x = [[1,2,3],[4,5,6],[7,8,9],[10,11,12]]

y = [[1,2],[1,2],[3,4]]

import numpy as np # I want to check my solution with numpy

mx = np.matrix(x)

my = np.matrix(y)

Result:

>>> matmult(x,y)

[[12, 18], [27, 42], [42, 66], [57, 90]]

>>> mx * my

matrix([[12, 18],

[27, 42],

[42, 66],

[57, 90]])

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值