Matlab:优化这个?

时间:2011-09-30 11:49:26

标签: optimization matlab vectorization

我是matlab的新手。一直负责加快程序。我确定有更好的方法来执行以下语句:

for i = 2:length(WallId)
     if WallId(i) ~= WallId(i-1)
        ReducedWallId = [ReducedWallId;WallId(i)];
        ReducedWallTime = [ReducedWallTime;WallTime(i)];
        GroupCount = [GroupCount;tempCount];
        tempCount = 1;
    else
        tempCount = tempCount +1;
    end
end

我可以预先将各种变量分配给'length(WallId)',但是在完成之后如何处理额外的变量呢?我在乎吗?

2 个答案:

答案 0 :(得分:3)

idx = find([true diff(WallId) ~= 0]);
ReducedWallId = WallId(idx);
ReducedWallTime = WallTime(idx);
GroupCount = diff([idx numel(WallId)+1]);

假设你想要的是WallId和WallTime中唯一数据的摘要,那么你应该这样做 确保首先对WallId进行排序。您可以重新组织WallTime以匹配,如下所示:

[WallId, ind] = sort(WallId);
WallTime = WallTime(ind);

此外,如果WallTime与WallId匹配,你只会得到正确答案。

答案 1 :(得分:2)

使用矢量化。

ReducedWallId=WallId(find(diff(WallId)~=0));

和ReducedWallTime类似。

显式for循环非常慢。使用矢量操作可以大大提高速度。这是优化MATLAB代码的一般主题,在网络上的各种文档中都有详细介绍。