python - python - 如何在python中为矩阵或二维数组的每个元素设置特定条件?
问题描述
我有多个矩阵,我想根据我之前创建的矩阵创建另一个“g”。我有一个通用公式来生成我的“g”矩阵,但是,我想根据我的矩阵“theta”更改其中的一些。如果“theta”中的一个元素的值为零,我想获取该元素的位置并在“g”中找到具有相同位置的元素以应用第二个公式。
目前,我在下面有这段代码。但问题是它运行得很慢。我必须生成多个与此类似的矩阵,我想知道是否有人知道更快的方法?先感谢您!
import numpy as np
np.seterr(divide='ignore', invalid='ignore')
x = np.linspace(-100.0, 100.0, 401)
y = np.linspace(100.0, -100.0, 401)
xx, yy = np.meshgrid(x, y)
xxx = xx / 10
yyy = yy / 10
r = np.sqrt((xxx ** 2.0) + (yyy ** 2.0))
theta = np.degrees(np.arctan(xxx / yyy))
m = 1.5
uv = (xxx * xxx) + ((yyy - (m / 2)) * (yyy + (m / 2)))
umag = np.sqrt((xxx ** 2) + ((yyy - (m / 2)) ** 2))
vmag = np.sqrt((xxx ** 2) + ((yyy + (m / 2)) ** 2))
theta2 = np.arccos(uv / (umag * vmag))
g = np.absolute(theta2 * 1000 / (m * xxx))
l = len(g)
for a in range(l):
for b in range(len(g[a])):
if (theta[a][b] == 0):
g[a][b] = 1 * 1000 / ((r[a][b]**2) - ((m**2) / 4))
print(g)
else:
pass
解决方案
您可以使用np.where(theta == 0)
. 它返回元组。
>>> a
array([[1, 2],
[2, 3],
[5, 6]])
>>> np.where(a==2)
(array([0, 1]), array([1, 0]))
检查此以获取更多详细信息
推荐阅读
- java - 要从父方获取的 ID - Hibernate 一对一关系
- reactjs - 将选择标签连接到表单,然后在提交时将其重置
- angular - Primeng p-calendar 与父级大小相同
- r - 如何使用 fct_relevel 函数重新调整因子列?
- python-3.x - 生成带有 utf-8 值的链接并将其传递给 Flask 路由
- python - 使用键盘模块时检测按键释放
- flutter - 为 Flutter 中的所有按钮设置 fontFamily
- php - Codeigniter:我可以将数组传递给 $ci->db->select() 吗?
- algorithm - 解释为什么这个算法是 n^2
- flutter - Firestore 中等效的 SQL IN 运算符