首页 > 解决方案 > How do I assign values to an array depending on condition (MATLAB→Python translation)

问题描述

Here is a portion of the MATLAB code I was able to run (excluding other non-important variables). For context, the full MATLAB program simulates band excitation response in from an atomic force microscope (not relevant to code error)

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 );

Now I am in the process of converting the code to Python. This is what I have so far

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))

However, now I am completely lost as to how I would convert the line D_vec( ((abs(w_vec)<w2) + (abs(w_vec)>w1)) == 2 ) = 1; to Python. It isn't my MATLAB code but it looks like it's attempting to assign a value to a function call, I'm not sure why nor am I sure what the line actually does. Does anyone have an idea of how I would convert this line to Python?

标签: pythonpython-3.xmatlabfunctionvariable-assignment

解决方案


tmp = ((abs(w_vec)<w2) + (abs(w_vec)>w1)) == 2MATLAB 中的语句返回一个逻辑 (true/false) 数组,其中tmp[i]ifw_vec[i] < w2 w_vec[i] > w1为 true 。Matlab 将真/假值隐式转换为 0 或 1,因此检查总和是否等于 2 相当于检查两个子条件是否都满足。

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

请注意,这^是 Python 中的 XOR 运算符,而不是幂运算符。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));

推荐阅读