• Matlab与Python的reshape使用区别


    经过测试,发现二维的话,Python需要先转置再用reshape。

    三维的话,Matlab则要对每一页先转置展开为一维,然后再把每一页拼起来,然后再按列往新数组中填充个,具体如下代码,Python的结果和Matlab一致,函数支持一维转二维,二维转二维,二维转三维,三维转二维,三维转三维。注意:在Maltab中假设数组形状为a,b,c,则在Python要改为c,a,b。

    1. import numpy as np
    2. def myreshape(x: np.ndarray, dim: tuple) -> np.ndarray:
    3. flag = False
    4. if np.iscomplexobj(x):
    5. flag = True
    6. if flag:
    7. res = np.zeros(dim, dtype=complex)
    8. else:
    9. res = np.zeros(dim)
    10. if len(x.shape) == 1:
    11. if len(dim) == 2:
    12. m, n = dim
    13. temp = x.flatten()
    14. for i in range(n):
    15. res[:, i] = temp[m * i:m * (i + 1)]
    16. elif len(x.shape) == 2:
    17. if len(dim) == 2:
    18. m, n = dim
    19. res = x.T.reshape((m, n))
    20. else:
    21. l, m, n = dim
    22. temp = x.T.flatten()
    23. idx = 0
    24. for i in range(l):
    25. for j in range(n):
    26. res[i, :, j] = temp[m * idx:m * (idx + 1)]
    27. idx += 1
    28. else:
    29. if len(dim) == 2:
    30. m, n = dim
    31. l1, m1, n1 = x.shape
    32. if flag:
    33. temp = np.zeros(l1 * m1 * n1, dtype=complex)
    34. else:
    35. temp = np.zeros(l1 * m1 * n1)
    36. for i in range(l1):
    37. temp[(m1 * n1) * i:(m1 * n1) * (i + 1)] = x[i, :, :].T.ravel()
    38. for i in range(n):
    39. res[:, i] = temp[m * i:m * (i + 1)]
    40. else:
    41. l, m, n = dim
    42. l1, m1, n1 = x.shape
    43. if flag:
    44. temp = np.zeros(l1 * m1 * n1, dtype=complex)
    45. else:
    46. temp = np.zeros(l1 * m1 * n1)
    47. for i in range(l1):
    48. temp[(m1 * n1) * i:(m1 * n1) * (i + 1)] = x[i, :, :].T.ravel()
    49. idx = 0
    50. for i in range(l):
    51. for j in range(n):
    52. res[i, :, j] = temp[m * idx:m * (idx + 1)]
    53. idx += 1
    54. return res
    55. a = np.array([[[1j, 2], [3, 4]], [[5, 6], [7, 8]], [[9, 10], [11, 12]]])
    56. b = myreshape(a, (2, 3, 2))
    57. aa = np.array([[1, 2], [3, 4], [5, 6], [7, 8]])
    58. print(aa.T.reshape(1, -1))
    59. print(aa.reshape(-1, 1))
    60. c = np.iscomplexobj(a)

  • 相关阅读:
    深入浅出Spring(27)
    【愚公系列】2022年11月 Redis数据库-Lua脚本的使用
    MyBatis数据脱敏
    [React]生命周期
    多媒体展厅总包制作会面临的问题分析
    java-php-python-ssm基于专家系统房产营销智能推荐系统计算机毕业设计
    前端学习| 第二章
    从零开始写 Makefile
    InnoDB索引机制
    CM311-1a_CH_S905L3A_安卓9.0_纯净线刷固件包
  • 原文地址:https://blog.csdn.net/Sanfenpai6/article/details/133829904