【python】numpy实现:预先指定一个复数矩阵,然后将两个实数矩阵所合成的复数矩阵结果放在其中

numpy实现:预先指定一个复数矩阵,然后将两个实数矩阵所合成的复数矩阵结果放在其中

1、不预先指定,直接将两个实数矩阵合为一个复数矩阵

方法1:

Complex_Mat = Real_Mat[0, :, :] + 1j * Real_Mat[1, :, :]

方法2:

Complex_Mat = 1j * Real_Mat[1, :, :]
Complex_Mat += Real_Mat[0, :, :]

其中,第二种方法大家说更节省内存。

2、若出于某种需求,需使用numpy预先初始化一个复数矩阵存放结果

这种情况下最需要注意的是:预先声明的这个矩阵的类型dtype一定得指定为复数complex

Complex_Mat = np.zeros((1, 4, 4), dtype=complex)  # 注意dtype,否则下方的语句执行后Complex_Mat中只存放实数
Complex_Mat = Real_Mat[0, :, :] + 1j * Real_Mat[1, :, :]

将一个4维实数矩阵转换为3维的复数矩阵的简单函数代码如下:

def Real2Complex(Real_Mat):
    """

    :param Real_Mat: 实数矩阵 (2*n, h, w, c) 输出样本数为2n(1-n为实部,n-2n为虚部),h和w为行和列,c为通道数
    :return: 复数矩阵 (n, h, w) n为样本数,h和w为行和列
    """
    Real_Mat = np.squeeze(Real_Mat, axis=3)
    n, h, w = Real_Mat.shape
    Complex_Mat = np.zeros((n // 2, h, w), dtype=complex)
    for idx in range(len(Complex_Mat)):
        Complex_Mat[idx, :, :] = Real_Mat[idx, :, :] + 1j * Real_Mat[idx + len(Complex_Mat), :, :]
    return Complex_Mat

猜你喜欢

转载自blog.csdn.net/phdongou/article/details/113768421