Python稀疏矩阵的转置

本文阅读 1 分钟
首页 Python笔记 正文
  1. '''
  2. 稀疏矩阵的转置
  3. 输入: 一个稀疏矩阵
  4. 输出: 矩阵的转置
  5. 方法: 中间可以利用三元组进行操作
  6. '''
  7. from numpy import *
  8. def sparseToTriple(matrix):
  9. m, n = shape(matrix)
  10. triple = []
  11. for i in range(m):
  12. for j in range(n):
  13. if matrix[i][j] != 0:
  14. triple.append([i, j, matrix[i][j]])
  15. return triple
  16. def transTriple(triple):
  17. m, n = shape(triple)
  18. transMatrix = []
  19. sortedIndex = array([m[1] for m in triple]).argsort()
  20. for i in range(m):
  21. tempArray = triple[sortedIndex[i]]
  22. transMatrix.append([tempArray[1], tempArray[0], tempArray[2]])
  23. return transMatrix
  24. def tripleToSparse(triple, m, n):
  25. outMatrix = zeros([n, m])
  26. for pointTuple in triple:
  27. mLocation = pointTuple[0]
  28. nLocation = pointTuple[1]
  29. value = pointTuple[2]
  30. outMatrix[mLocation][nLocation] = value
  31. return outMatrix
  32. def matrixTrans(matrix):
  33. m, n = shape(matrix)
  34. triple = sparseToTriple(matrix)
  35. transedTriple = transTriple(triple)
  36. transedMatrix = tripleToSparse(transedTriple, m, n)
  37. return transedMatrix
  38. matrix = [[0, 0, 0, 0, 0, 0, 6, 0, 0],
  39. [0, 0, 2, 0, 0, 1, 0, 0, 0],
  40. [0, 0, 0, 0, 0, 0, 0, 0, 0],
  41. [3, 0, 0, 0, 0, 0, 0, 0, 0],
  42. [0, 0, 0, 0, 0, 0, 0, 5, 0],
  43. [0, 7, 0, 0, 0, 0, 0, 0, 0],
  44. [0, 0, 0, 0, 0, 0, 0, 0, 8],
  45. [0, 0, 5, 0, 0, 0, 0, 0, 0],
  46. [0, 0, 0, 0, 0, 0, 0, 0, 0],
  47. [0, 0, 0, 2, 0, 0, 0, 0, 0]]
  48. transedMatrix = matrixTrans(matrix)
  49. print(transedMatrix)
解压密码: detechn或detechn.com

免责声明

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

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

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

Python利用三元组完成稀疏矩阵相乘
« 上一篇 01-21
Python二叉搜索树的后续遍历序列
下一篇 » 01-21

发表评论

惪特博客
  • 文章总数:
    18497 篇
  • 评论总数:
    53318 条
  • 标签总数:
    8873 个
  • 总浏览量:
    22650585 次
  • 最后更新:
    6天前

最多点赞

随便看看

标签TAG