【问题标题】:speed up this matlab code?加速这个matlab代码?
【发布时间】:2011-11-16 20:30:12
【问题描述】:

有没有一种好方法可以使用矩阵运算或其他任何方法来加速这个 matlab 代码块(尤其是n,可能很大)?我超过 1/4 的执行时间都在这个小代码块中。

% Get the bin indexes that we will place the network in
bins = [];
for n=low_freq:0.5:high_freq;
    bins = [bins, (n-spec_start)/spec_bin_size+1];
end

测试代码:

spec_start=2400
spec_bin_size=0.5
low_freq = 2437
high_freq=2438

bins = [];
for n=low_freq:0.5:high_freq;
    bins = [bins, (n-spec_start)/spec_bin_size+1];
end

bins  % 75 76 77

bins = [];
bins = (low_freq:0.5:high_freq - spec_start)./spec_bin_size + 1;

bins  % empty?

【问题讨论】:

    标签: performance matlab optimization


    【解决方案1】:

    你可以跳过循环:

    bins = ((low_freq:0.5:high_freq) - spec_start)./spec_bin_size + 1;
    

    在无法进行上述矢量化计算的情况下,至少应该preallocate the output array

    【讨论】:

    • @strictlyrude27:抱歉让你浪费了时间。
    • hmmmm,我觉得有些不对劲。我认为这个脚本的结果应该是 75,76,77 .. 但我从你的代码中得到一个空矩阵。已编辑问题中包含的测试代码。非常感谢您的帮助!
    • a-ha,对括号稍作调整:((low_freq:0.5:high_freq) - spec_start)./spec_bin_size + 1
    • 缺少方括号。这个怎么样:([low_freq:0.5:high_freq] - spec_start)./spec_bin_size + 1
    猜你喜欢
    • 2021-01-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-30
    • 1970-01-01
    • 1970-01-01
    • 2015-10-08
    相关资源
    最近更新 更多