找到一种方法,用不同的公式替换 np.ogrid 中的列,以获得可迭代对象的特定值
Finding a way to replace a column in an np.ogrid with a different formula for a specific value of the iterable
a,b=np.ogrid[0:n:1,0:n:1]
A=np.exp(1j*(np.pi/3)*np.abs(a-b))
a,b=np.diag_indices_from(A)
A[a,b]=1-1j/np.sqrt(3)
是我的基础。它产生一个网格,充当 n*n 矩阵。
我的问题是我需要替换网格中的一列,例如 b=17。
我需要此列为:
A=np.exp(1j*(np.pi/3)*np.abs(a-17+geo_mean(x)))
除了 a=b 需要保留的地方:
A[a,b]=1-1j/np.sqrt(3)
geo_mean(x) 只是伪随机数生成器确定的 50 个值的几何平均值,在我的代码中定义为:
x=[random.uniform(0,0.5) for p in range(0,50)]
def geo_mean(iterable):
a = np.array(iterable)
return a.prod()**(1.0/len(a))
那么我该如何替换一列以在指数公式中包含 geo_mean 并且不改变对角线值呢?
让我们先说 diag_indices_from()
在这里有点没用,因为我们已经知道对角线元素是那些具有相同索引 i
和 j
和 运行 的元素最高值 n
。因此,让我们在开始的时候稍微简化一下代码:
a, b = np.ogrid[0:n:1, 0:n:1]
A = np.exp(1j * (np.pi / 3) * np.abs(a - b))
diag = np.arange(n)
A[diag, diag] = 1 - 1j / np.sqrt(3)
现在,假设您想将 k
列的值 除了对角元素 设置为
np.exp(1j * (np.pi/3) * np.abs(a - 17 + geo_mean(x)))
(我猜上面公式中的a
是行索引)
这可以使用整数索引来完成,特别是它们几乎是计算出来的:我们已经有了 diag
,我们只需要从中删除需要保持不变的对角线元素的索引:
r = np.delete(diag, k)
然后
x = np.random.uniform(0, 0.5, (r.size, 50))
A[r, k] = np.exp(1j * (np.pi/3) * np.abs(r - k + geo_mean(x)))
但是,要使上述工作正常,您需要重写 geo_mean()
函数,使其适用于 2D 输入数组(我还将添加一些检查和转换以使其向后兼容):
def geo_mean(x):
x = np.asarray(x)
dim = len(x.shape)
x = np.atleast_2d(x)
v = np.prod(x, axis=1) ** (1.0 / x.shape[1])
return v[0] if dim == 1 else v
a,b=np.ogrid[0:n:1,0:n:1]
A=np.exp(1j*(np.pi/3)*np.abs(a-b))
a,b=np.diag_indices_from(A)
A[a,b]=1-1j/np.sqrt(3)
是我的基础。它产生一个网格,充当 n*n 矩阵。
我的问题是我需要替换网格中的一列,例如 b=17。
我需要此列为:
A=np.exp(1j*(np.pi/3)*np.abs(a-17+geo_mean(x)))
除了 a=b 需要保留的地方:
A[a,b]=1-1j/np.sqrt(3)
geo_mean(x) 只是伪随机数生成器确定的 50 个值的几何平均值,在我的代码中定义为:
x=[random.uniform(0,0.5) for p in range(0,50)]
def geo_mean(iterable):
a = np.array(iterable)
return a.prod()**(1.0/len(a))
那么我该如何替换一列以在指数公式中包含 geo_mean 并且不改变对角线值呢?
让我们先说 diag_indices_from()
在这里有点没用,因为我们已经知道对角线元素是那些具有相同索引 i
和 j
和 运行 的元素最高值 n
。因此,让我们在开始的时候稍微简化一下代码:
a, b = np.ogrid[0:n:1, 0:n:1]
A = np.exp(1j * (np.pi / 3) * np.abs(a - b))
diag = np.arange(n)
A[diag, diag] = 1 - 1j / np.sqrt(3)
现在,假设您想将 k
列的值 除了对角元素 设置为
np.exp(1j * (np.pi/3) * np.abs(a - 17 + geo_mean(x)))
(我猜上面公式中的a
是行索引)
这可以使用整数索引来完成,特别是它们几乎是计算出来的:我们已经有了 diag
,我们只需要从中删除需要保持不变的对角线元素的索引:
r = np.delete(diag, k)
然后
x = np.random.uniform(0, 0.5, (r.size, 50))
A[r, k] = np.exp(1j * (np.pi/3) * np.abs(r - k + geo_mean(x)))
但是,要使上述工作正常,您需要重写 geo_mean()
函数,使其适用于 2D 输入数组(我还将添加一些检查和转换以使其向后兼容):
def geo_mean(x):
x = np.asarray(x)
dim = len(x.shape)
x = np.atleast_2d(x)
v = np.prod(x, axis=1) ** (1.0 / x.shape[1])
return v[0] if dim == 1 else v