arrays - Matlab:如果索引在一个范围内,则对相应的值求和

标签 arrays matlab vectorization

我一直在疯狂地想办法加快速度。现在我当前的代码在 77000 个事件上循环约 200 秒。我希望有人能够帮助我加快速度,因为我必须完成其中大约 500 次。

问题: 我有数组(均为 200000x1),对应于超过 77000 个事件的能量和位置。我将每个事件的范围分成两个数组,event_start 和 event_end。我首先要做的是在特定范围内寻找位置,然后将相应的能量放入自己的数组中。为了从这些信息中获得我需要的信息,我循环遍历每个事件及其相应的开始/结束,以总结每个事件的所有能量。我的代码如下:

    indx_pos = find(pos>0.7 & pos<2.0);
    energy = HitEnergy(indx_pos);

    for i=1:n_events
        Etotal(i) = sum(energy(find(indx_pos>=event_start(i) …
        & indx_pos<=event_end(i))));    
    end

示例输入和输出:

% Sample input 
% pos and energy same length

n_events = 3;
event_start = [1 3 7]';
event_end   = [2 6 8]';

pos = [0.75 0.8 2.1 3.6 1.9 0.5 21.0 3.1]';
HitEnergy = [0.002 0.004 0.01 0.0005 0.08  0.1 1.7 0.007]';


%  Sample Output
Etotal = 0.0060
         0.0800
              0

最佳答案

方法 #1:一般情况

一种方法 bsxfun矩阵乘法 -

mask = bsxfun(@ge,indx_pos,event_start.') & bsxfun(@le,indx_pos,event_end.')
Etotal = energy.'*mask

如果 indx_pos 中有很多元素,这可能有点内存消耗


方法 #2:开始/结束范围不重叠的情况

可以使用 accumarray对于像这样的特殊情况 -

%// Setup ID array for use in accumarray later on
loc(numel(pos))=0; %// Fast pre-allocation scheme
valids = event_end+1<=numel(pos);
loc(event_end(valids)+1) = -1*(1:sum(valids));
loc(event_start) = loc(event_start)+(1:numel(event_end));
id = cumsum(loc);

%// Set elements as zeros in HitEnergy that do not satisfy the criteria:
%// pos>0.7 & pos<2.0
HitEnergy_select = (pos>0.7 & pos<2.0).*HitEnergy(:);

%// Discard elments in HitEnergy_select & id that have IDs as zeros  
HitEnergy_select = HitEnergy_select(id~=0);
id = id(id~=0);

%// Accumulate summations as done inside the loop in the original code 
Etotal = accumarray(id(:),HitEnergy_select);

关于arrays - Matlab:如果索引在一个范围内,则对相应的值求和,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29393234/

相关文章:

java.lang.OutOfMemoryError : Java heap space when using this short program to Remove title bar 错误

c - 将 mex 文件链接到静态 mpfr 库时出现问题

python - 如何在不循环的情况下将多个矩阵相乘?

r - 在 R 中快速替换所选矩阵条目

matlab - 在 MATLAB 中修改决策树的精度

r - 将 runif() 应用于下限和上限向量

c - 指针算术我不清楚

php - 如何从 PHP 中的数组填充组合框?

javascript,比较不同大小的数组

java - 设置数组的值不起作用 - 为什么?