如何为 python 中的矩阵或二维数组的每个元素设置特定条件?
How to have specific conditions per element for a matrix or 2d array in 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)
。它 returns 元组。
>>> a
array([[1, 2],
[2, 3],
[5, 6]])
>>> np.where(a==2)
(array([0, 1]), array([1, 0]))
查看this了解更多详情
好的,效果很好。我将我的 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))
由于取消了对所有元素的检查,它运行得更快了。代码现在只检查满足条件的地方。
非常感谢!!
我有多个矩阵,我想根据我之前创建的矩阵创建另一个 '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)
。它 returns 元组。
>>> a
array([[1, 2],
[2, 3],
[5, 6]])
>>> np.where(a==2)
(array([0, 1]), array([1, 0]))
查看this了解更多详情
好的,效果很好。我将我的 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))
由于取消了对所有元素的检查,它运行得更快了。代码现在只检查满足条件的地方。 非常感谢!!