Numpy二维标量场网格过滤结果异常的原因探究
为什么“naive filtering”无法正确提取二维标量场的目标区域?
我正在尝试理解为何标注为"naive filtering"的代码块无法提取二维标量场的预期角落区域,而标注为"correct result"的代码块可以实现该效果。相关代码如下:
import numpy as np import matplotlib.pyplot as plt # creating the underlying x and y axes nx, ny = 101, 111 x = np.linspace(-1, 1, nx) y = np.linspace(-1, 1, ny) X, Y = np.meshgrid(x, y, indexing='xy') # computing the scalar 2D field f = np.exp(-1.1*X*X - 0.9*Y*Y + 0.7*X*Y) # saving figure fig, ax = plt.subplots() ax.imshow(f) plt.savefig('field_full.png') # data filters mx = x > 0 my = y < 0 MX, MY = np.meshgrid(mx, my, indexing='xy') # naive filtering mf = (MX & MY) lf = f[mf].reshape(len(x[mx]), len(y[my])) # saving figure fig, ax = plt.subplots() ax.imshow(lf) plt.savefig('field_filtered_naive.png') # correct result mf = (MX & MY).T lf = f.T[mf].reshape(len(x[mx]), len(y[my])) # saving figure fig, ax = plt.subplots() ax.imshow(lf) plt.savefig('field_filtered_correct.png')
编辑:在看到@Mercury的回答后,我明确了需求:我清楚如何得到预期结果,但困惑的是"naive filtering"代码块为何无法直接生效。此外,@Mercury提出的另一种可行代码:
import numpy as np import matplotlib.pyplot as plt # creating the underlying x and y axes nx, ny = 101, 111 x = np.linspace(-1, 1, nx) y = np.linspace(-1, 1, ny) X, Y = np.meshgrid(x, y, indexing='xy') # computing the scalar 2D field f = np.exp(-1.1*X*X - 0.9*Y*Y + 0.7*X*Y) # saving figure fig, ax = plt.subplots() ax.imshow(f) plt.savefig('field_full.png') # data filters mx = x > 0 my = y < 0 MX, MY = np.meshgrid(mx, my, indexing='xy') # filtered field data mf = (MX & MY) reduced_nx = len(x[mx]) reduced_ny = len(y[my]) lf = f[mf].reshape(reduced_ny, reduced_nx) # saving figure fig, ax = plt.subplots() ax.imshow(lf) plt.savefig('field_filtered.png')
这让我更困惑,我特意定义了reduced_nx和reduced_ny来凸显问题:原场f的维度为nx×ny,但过滤后的lf维度却需设为reduced_ny×reduced_nx而非预期的相反顺序,这种"隐性转置"看似设计缺陷,易导致难以察觉的错误。
内容的提问来源于stack exchange,提问作者ragdollfun
相关产品推荐
相关产品推荐

