Matlab:优化这个(第2页)

时间:2011-09-30 15:58:46

标签: optimization matlab vectorization

这是另一个:

ValidFirings = ((DwellTimes > 30/(24*60*60)) | (GroupCount > 1));

for i = length(ValidFirings):-1:2
    if(~ValidFirings(i))
        DwellTimes(i-1) = DwellTimes(i)+DwellTimes(i-1);
        GroupCount(i-1) = GroupCount(i)+GroupCount(i-1);
        DwellTimes(i) = [];
        GroupCount(i) = [];
        ReducedWallTime(i) = [];
        ReducedWallId(i) = [];
    end
end

似乎意图是根据传感器触发是否有效来总结“停留时间”。所以我有一个传感器点火向量,如果当前行没有标记为有效,我会向后走,然后汇总到前一行。

我可以在C / C ++中看到这个,但我不知道如何将它转换为更好的Matlab矢量符号。现在看来,这个循环很慢。

编辑: 我可以使用某种形式的DwellTimes = DwellTimes(cumsum(ValidFirings))吗?

2 个答案:

答案 0 :(得分:2)

与上一个问题一样,替换for循环可以提高性能。

%# Find the indices for invalid firings
idx = find(~(DwellTimes > 30/(24*60*60)) | (GroupCount > 1));

%# Index the appropriate elements and add them (start the addition
%# from the second element)
%# This eliminates the for loop
DwellTimes(idx(2:end)-1) = DwellTimes(idx(2:end)-1)+DwellTimes(idx(2:end));
GroupCount(idx(2:end)-1) = GroupCount(idx(2:end)-1)+GroupCount(idx(2:end));

%# Now remove all the unwanted elements (this removes the 
%# first element if it was a bad firing.  Modify as necessary)
GroupCount(idx)=[];
DwellTimes(idx)=[];

答案 1 :(得分:1)

我会先显示合并,然后消除无效数据。这样可以避免不断调整数据大小。请注意,由于值传播的方式,您无法反转FOR循环的顺序。

ValidFirings = ((DwellTimes > 30/(24*60*60)) | (GroupCount > 1));

for i = length(ValidFirings):-1:2
    if (~ValidFirings(i))
        DwellTimes(i-1) = DwellTimes(i) + DwellTimes(i-1);
        GroupCount(i-1) = GroupCount(i) + GroupCount(i-1);
    end
end

DwellTimes      = DwellTimes(ValidFirings);
GroupCount      = GroupCount(ValidFirings);
ReducedWallTime = ReducedWallTime(ValidFirings);
ReducedWallId   = ReducedWallId(ValidFirings);