在python中,如何为矩阵或2d数组的每个元素设置特定的条件?

2024-09-28 21:55:06 发布

您现在位置:Python中文网/ 问答频道 /正文

我有多个矩阵,我想在我之前创建的矩阵的基础上创建另一个“g”。我有一个生成‘g’矩阵的一般公式,但是,我想根据矩阵‘θ’来修改其中的一些公式。如果“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

Tags: 元素np矩阵sqrtuvxxx公式ignore
2条回答

好吧,结果很好。我把for循环改成了这个:

 row, col = np.where(theta == 0)

 for elements in g[row,col]:
     g[row,col] = 1 * 1000 / ((r[row,col]**2) - ((m**2) / 4))

现在它运行得快得多,所有元素的检查都被取消了。代码现在只检查满足条件的地方。 非常感谢

您可以使用np.where(theta == 0)。它返回元组

>>> a
array([[1, 2],
       [2, 3],
       [5, 6]])
>>> np.where(a==2)
(array([0, 1]), array([1, 0]))

有关详细信息,请查看this

相关问题 更多 >