2011-09-30 123 views
2

对vb新来matlab。一直负责加快程序。我敢肯定有一个更好的方式来做到以下语句: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 

我可以预先分配的各种增值经销商为“长(WallId)”,但我该怎么做了之后做额外的?我关心的?

回答

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一样。

+0

你能解释'GroupCount'这条线的工作原理吗?我在那里得到'horzcat'错误。让我觉得我错了。 – ethrbunny

+0

我现在明白了。是否缺少分号?可能由网站裁剪出来。 – ethrbunny

+0

取决于WallId向量的方向。我的版本假设它是一个行向量。如果它是列向量,那么您将需要添加一些分号,如建议。 – Nzbuu

2

使用矢量化。

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

和类似的ReducedWallTime。

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

+0

那么我将如何获得计数呢? – ethrbunny

+0

您可以使用统计工具箱中的tabulate()函数:y = tabulate(WallId);计数= Y(:,2); – thias

+2

你不需要使用'find'。 'ReducedWallId = WallId(diff(WallId)〜= 0);'会更快并且效果相同。查找逻辑下标。 – Nzbuu