如何根据条件给数组赋值(MATLAB→Python翻译)

How do I assign values to an array depending on condition (MATLAB→Python translation)

这是我能够 运行 的 MATLAB 代码的一部分(不包括其他不重要的变量)。对于上下文,完整的 MATLAB 程序模拟来自原子力显微镜的带激发响应(与代码错误无关)

IO_rate = 4E6; %[samples/sec]
w1 = 200E3; % lower edge of band
w2 = 400E3; % upper edge of band
N_pixels = 128; % number of pixels along a line scan
N_points_per_pixel = 2^13; % number of data points per pixel
w_vec = -IO_rate/2: IO_rate/N_points_per_pixel : IO_rate/2-IO_rate/N_points_per_pixel; %frequency vector over a pixel

% build drive signal, define in the Fourier domain
D_vec = zeros(size(w_vec));
D_vec( ((abs(w_vec)<w2) + (abs(w_vec)>w1)) == 2 ) = 1; % drive bins located within upper and lower band edges
band_ind = find( (((w_vec)<w2) + ((w_vec)>w1)) == 2 );

现在我正在将代码转换为 Python。这是我目前所拥有的

IO_rate = 4E6; #[samples/sec]
w1 = 200E3; # lower edge of band
w2 = 400E3; # upper edge of band
N_pixels = 128; # number of pixels along a line scan
N_points_per_pixel = 2^13; # number of data points per pixel
w_vec = np.arange(-IO_rate/2, IO_rate/2-IO_rate/N_points_per_pixel, IO_rate/N_points_per_pixel)
D_vec = np.zeros(np.size(w_vec))

但是,现在我完全不知道如何将行 D_vec( ((abs(w_vec)<w2) + (abs(w_vec)>w1)) == 2 ) = 1; 转换为 Python。这不是我的 MATLAB 代码,但它看起来像是在尝试为函数调用赋值,我不确定为什么,也不确定该行实际做了什么。有谁知道我如何将此行转换为 Python?

MATLAB 中的语句 tmp = ((abs(w_vec)<w2) + (abs(w_vec)>w1)) == 2 returns 一个逻辑 (true/false) 数组,其中 tmp[i] 为真,如果 w_vec[i] < w2 并且 w_vec[i] > w1。 Matlab 将 true/false 值隐式转换为 0 或 1,因此检查和是否等于 2 等同于检查是否满足 both 子条件。

一旦我们有了这个数组,我们就可以用它来将Dvec中的相应条目设置为1。

注意^是Python中的异或运算符,不是幂运算符。 a ^ b 在 MATLAB 中等同于 a**bpow(a,b) 在 Python.

这是我的转换:

  IO_rate = 4E6; #[samples/sec]
  w1 = 200E3; # lower edge of band
  w2 = 400E3; # upper edge of band
  N_pixels = 128; # number of pixels along a line scan
  N_points_per_pixel = pow(2,13); # number of data points per pixel

  #Note the +1 in the second argument of arange
  w_vec = np.arange(-IO_rate/2, IO_rate/2-IO_rate/N_points_per_pixel + 1, IO_rate/N_points_per_pixel);
  D_vec = np.zeros(np.size(w_vec));

  #Find the indices that satisfy both conditions
  ind = (abs(w_vec)<w2) & (abs(w_vec)>w1);
  D_vec[ind] = 1; #assign those indices to 1.

  band_ind = np.nonzero(((w_vec)<w2) & ((w_vec)>w1));

创建新数组的 Numpy 习惯用法是 numpy.where

因为我 in ,

D = np.where(np.logical_and(np.abs(v)>low, np.abs(v)<hi), 1, 0)