簡體   English   中英

如何使用 numpy.ma.masked_inside

[英]How to use numpy.ma.masked_inside

numpy.ma.masked_where用於屏蔽單個值。 還有numpy.ma.masked_inside用於屏蔽間隔。

但是我不太明白它應該如何工作。

我找到了這個片段

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

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

但結果不是我想要的,它只是一條直線......我想要的東西像這樣

整個腳本是這樣的:

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)

然后輸出看起來幾乎就像你鏈接的那個:

在此處輸入圖片說明

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM