2011-09-30 119 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