我正在尝试使用2个实值矩阵(在Pytorch中,但此处仅出于说明目的使用numpy)来表示复数矩阵。
目前,我正在这样做:
import numpy as np
# represent real
X = np.random.randn(10,10)
# represent imaginary
I = np.random.randn(10,10)
# build complex matrix using the identity
real = np.concatenate([X, -I], axis=-1)
img = np.concatenate([I, X], axis=-1)
complex_W = np.concatenate([real, img,], axis=0)
# is complex_W now correctly represented??
我也可以这样吗?
# represent real
X = np.random.randn(10,10)
# represent imaginary
I = np.random.randn(10,10)
complex_W = X + I
答案 0 :(得分:0)
您可以使用numpy数组实现复杂的ndarray数据结构。您可能希望将实零件存储在datasture的一个变量中,将复数存储在anthor变量中。 Python提供了一种重载某些运算符的方法,包括+
,-
,*
,/
。例如,我下面的类使用三个运算符(+,-,*)来实现复杂的数据结构
class ComplexNDArray(object):
def __init__(self, real, imaginary):
self.real = real
self.imaginary = imaginary
@property
def real(self):
return self.__real
@real.setter
def real(self, value):
if type(value) == np.ndarray:
self.__real = value
elif isinstance(value, (int, float, list, tuple)):
self.__real = np.array(value)
else:
raise ValueError("Unsupported type value:%s" % (str(type(value))))
@property
def imaginary(self):
return self.__imaginary
@imaginary.setter
def imaginary(self, value):
if type(value) == np.ndarray:
self.__imaginary = value
elif isinstance(value, (int, float, list, tuple)):
self.__imaginary = np.array(value)
else:
raise ValueError("Unsupported type value:%s" % (str(type(value))))
def __add__(self, other):
real = self.real + other.real
imaginary = self.imaginary + other.imaginary
return ComplexNDArray(real, imaginary)
def __sub__(self, other):
real = self.real - other.real
imaginary = self.imaginary - other.imaginary
return ComplexNDArray(real, imaginary)
def __mul__(self, other):
real = self.real * other.real - self.imaginary * other.imaginary
imaginary = self.real * other.imaginary + self.imaginary * other.real
return ComplexNDArray(real, imaginary)
def __str__(self):
return str(self.real) + "+"+str(self.imaginary)+"i"
现在您可以使用此数据结构执行一些操作。
a = np.array([1, 2,3])
b = np.array([4, 5, 1])
c = np.array([4, 7,3])
d = np.array([5, 1,7])
cmplx = ComplexNDArray(a, b)
cmplx2 = ComplexNDArray(c, d)
print(cmplx) # [1 2 3]+[4 5 1]i
print(cmplx2) # [4 7 3]+[5 1 7]i
print(cmplx+cmplx2) # [5 9 6]+[9 6 8]i
print(cmplx-cmplx2) # [-3 -5 0]+[-1 4 -6]i
print(cmplx*cmplx2) # [-16 9 2]+[21 37 24]i