Matlab与Python的reshape使用区别

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

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

import numpy as np


def myreshape(x: np.ndarray, dim: tuple) -> np.ndarray:
    flag = False
    if np.iscomplexobj(x):
        flag = True
    if flag:
        res = np.zeros(dim, dtype=complex)
    else:
        res = np.zeros(dim)
    if len(x.shape) == 1:
        if len(dim) == 2:
            m, n = dim
            temp = x.flatten()
            for i in range(n):
                res[:, i] = temp[m * i:m * (i + 1)]
    elif len(x.shape) == 2:
        if len(dim) == 2:
            m, n = dim
            res = x.T.reshape((m, n))
        else:
            l, m, n = dim
            temp = x.T.flatten()
            idx = 0
            for i in range(l):
                for j in range(n):
                    res[i, :, j] = temp[m * idx:m * (idx + 1)]
                    idx += 1
    else:
        if len(dim) == 2:
            m, n = dim
            l1, m1, n1 = x.shape
            if flag:
                temp = np.zeros(l1 * m1 * n1, dtype=complex)
            else:
                temp = np.zeros(l1 * m1 * n1)
            for i in range(l1):
                temp[(m1 * n1) * i:(m1 * n1) * (i + 1)] = x[i, :, :].T.ravel()
            for i in range(n):
                res[:, i] = temp[m * i:m * (i + 1)]
        else:
            l, m, n = dim
            l1, m1, n1 = x.shape
            if flag:
                temp = np.zeros(l1 * m1 * n1, dtype=complex)
            else:
                temp = np.zeros(l1 * m1 * n1)
            for i in range(l1):
                temp[(m1 * n1) * i:(m1 * n1) * (i + 1)] = x[i, :, :].T.ravel()
            idx = 0
            for i in range(l):
                for j in range(n):
                    res[i, :, j] = temp[m * idx:m * (idx + 1)]
                    idx += 1
    return res


a = np.array([[[1j, 2], [3, 4]], [[5, 6], [7, 8]], [[9, 10], [11, 12]]])
b = myreshape(a, (2, 3, 2))
aa = np.array([[1, 2], [3, 4], [5, 6], [7, 8]])
print(aa.T.reshape(1, -1))
print(aa.reshape(-1, 1))
c = np.iscomplexobj(a)

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

空花缱绻三分

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值