Python利用三元组完成稀疏矩阵相乘

本文阅读 1 分钟
首页 Python笔记 正文
  1. '''
  2. 利用三元组完成稀疏矩阵相乘
  3. '''
  4. from numpy import *
  5. def sparseToTriple(matrix):
  6. m, n = shape(matrix)
  7. triple = []
  8. for i in range(m):
  9. for j in range(n):
  10. if matrix[i][j] != 0:
  11. triple.append([i, j, matrix[i][j]])
  12. return triple
  13. def multiTriple(tripleA, tripleB):
  14. rowA = shape(tripleA)[0]
  15. rowB = shape(tripleB)[0]
  16. multiMatrix = []
  17. for i in range(rowA):
  18. for j in range(rowB):
  19. if tripleA[i][1] == tripleB[j][0]:
  20. multiMatrix.append([tripleA[i][0], tripleB[j][1], tripleA[i][2]*tripleB[j][2]])
  21. return multiMatrix
  22. def tripleToSparse(triple, m, n):
  23. outMatrix = zeros([m, n])
  24. for pointTuple in triple:
  25. mLocation = pointTuple[0]
  26. nLocation = pointTuple[1]
  27. value = pointTuple[2]
  28. outMatrix[mLocation][nLocation] = value
  29. return outMatrix
  30. def matrixMultiple(matrixA, matrixB):
  31. mA, nA = shape(matrixA)
  32. mB, nB = shape(matrixB)
  33. if nA != mB:
  34. print("the two matries doesn't match!")
  35. return -1
  36. tripleA = sparseToTriple(matrixA)
  37. tripleB = sparseToTriple(matrixB)
  38. multiTriples = multiTriple(tripleA, tripleB)
  39. print(multiTriples)
  40. multiMatrix = tripleToSparse(multiTriples, mA, nB)
  41. return multiMatrix
  42. matrixA = [[3, 0, 0, 7],
  43. [0, 0, -1, 0],
  44. [-1, -2, 0, 0],
  45. [0, 0, 0, 2]]
  46. matrixB = [[0, 0, -2, 0, -1],
  47. [0, 0, -3, 0, 0],
  48. [-1, 0, 0, 0, 0],
  49. [0, 0, 0, 3, 0]]
  50. ans = matrixMultiple(matrixA, matrixB)
  51. print(ans)
解压密码: detechn或detechn.com

免责声明

本站所有资源出自互联网收集整理,本站不参与制作,如果侵犯了您的合法权益,请联系本站我们会及时删除。

本站发布资源来源于互联网,可能存在水印或者引流等信息,请用户自行鉴别,做一个有主见和判断力的用户。

本站资源仅供研究、学习交流之用,若使用商业用途,请购买正版授权,否则产生的一切后果将由下载用户自行承担。

Python机器人的运动范围
« 上一篇 01-21
Python稀疏矩阵的转置
下一篇 » 01-21

发表评论