开发者

Matlab: Optimize this (pt 2)

开发者 https://www.devze.com 2023-04-10 08:03 出处:网络
Here\'s another one: ValidFirings = ((DwellTimes > 30/(24*60*60)) | (GroupCount > 1)); for i = length(ValidFirings):-1:2

Here's another one:

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

It appears that the intent is to sum up 'dwelltimes' based on whether or not the sensor firing is considered valid. So I have a vector of sensor firings that Im walking through backwards and summing into the previous row if the current row is not marked as valid.

I can visualize this in C/C++ but I don't know how to translate it into better Matlab vector notation. As it stands now, this loop is v slow.

EDIT: Could I use some form of DwellTimes = DwellTimes( cumsum( ValidFirings ))?


As with your previous question, replacing the for loop should improve the performance.

%# 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)=[];


I would consolidate first as shown, then eliminate the invalid data. This avoids the constant resizing of the data. Note that you can't reverse the order of the FOR loop due to the way that the values propagate.

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

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号