首页 > 解决方案 > 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

标签: pythonpython-3.xpython-2.7numpynumpy-ndarray

解决方案


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

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

检查以获取更多详细信息


推荐阅读