python - 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?
解决方案
tmp = ((abs(w_vec)<w2) + (abs(w_vec)>w1)) == 2
MATLAB 中的语句返回一个逻辑 (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**b
或pow(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));
推荐阅读
- java - Android:按钮 onClick 从 ArrayList 获取随机数据
- polymer-2.x - Polymer 2.0 在动态生成的纸卡上捕获长按
- c# - 对工作单元的依赖注入
- node.js - 从不同的微服务收集数据的正确方法是什么?
- ios - 故事板混乱:UITextView 和 UIView 不可见,UITextFields 不可编辑?
- azure - 通过 HTTP 使用 ServiceBusTrigger 调用 Azure 函数会引发 InvalidOperationException
- android - Android View.GONE 可访问性对讲错误
- mysql - 对表执行列表查询
- jekyll - jekyll markdownify 没有像我想象的那样工作
- java - 使用另一个类的字段更新现有的 Mongo 文档