gpt4 book ai didi

python - 如何使用 numpy.ma.masked_inside

转载 作者:太空宇宙 更新时间:2023-11-04 02:58:26 25 4
gpt4 key购买 nike

numpy.ma.masked_where 用于屏蔽单个值。还有用于屏蔽间隔的 numpy.ma.masked_inside

但是我不太明白它应该如何工作。

I found this snippet :

import numpy.ma as M              
from pylab import *

figure()

xx = np.arange(-0.5,5.5,0.01)
vals = 1/(xx-2)
vals = M.array(vals)
mvals = M.masked_where(xx==2, vals)

subplot(121)
plot(xx, mvals, linewidth=3, color='red')
xlim(-1,6)
ylim(-5,5)

但是,我想做这样的事情(我知道这是行不通的):

mvals = M.masked_where(abs(xx) < 2.001 and abs(xx) > 1.999, vals)

因此我尝试使用 masked_inside like this :

mvals = ma.masked_inside(xx, 1.999, 2.001)

但结果不是我想要的,它只是一条直线......我想要的是this之类的东西.

整个脚本是这样的:

def f(x):
return (x**3 - 3*x) / (x**2 - 4)

figure()
xx = np.arange(begin, end, precision)
vals = [f(x) for x in xx]
vals = M.array(vals)
mvals = ma.masked_inside(xx, 1.999, 2.001)
subplot(121)
plot(xx, mvals, linewidth=1, c='red')
xlim(-4,4)
ylim(-4,4)
gca().set_aspect('equal', adjustable='box')
show()

如何正确使用 masked_inside

最佳答案

问题不在于np.masked_inside,而在于您在哪个点上以及在哪个数组上使用它(您在之后应用了您的函数!) .

np.ma.masked_inside只是 np.ma.masked_where 的便利包装:

def masked_inside(x, v1, v2, copy=True):
# That's the actual source code
if v2 < v1:
(v1, v2) = (v2, v1)
xf = filled(x)
condition = (xf >= v1) & (xf <= v2)
return masked_where(condition, x, copy=copy)

如果你这样应用它:

import numpy as np
import matplotlib.pyplot as plt

def f(x):
return (x**3 - 3*x) / (x**2 - 4)

# linspace is much better suited than arange for such plots
x = np.linspace(-5, 5, 10000)
# mask the x values
mvals = np.ma.masked_inside(x, 1.999, 2.001)
mvals = np.ma.masked_inside(mvals, -2.001, -1.999)

# Instead of the masked_inside you could also use
# mvals = np.ma.masked_where(np.logical_and(abs(x) > 1.999, abs(x) < 2.001), x)

# then apply the function
vals = f(mvals)

plt.figure()
plt.plot(x, vals, linewidth=1, c='red')
plt.ylim(-6, 6)

然后输出看起来几乎与您链接的那个一样:

enter image description here

关于python - 如何使用 numpy.ma.masked_inside,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41687389/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com