當我在MatLab中執行這些等效操作時,第一個運行時間爲24.158371秒(for循環)。第二次運行在0.004976秒(邏輯索引)。 MatLab可能會做些什麼讓這個運行速度更快?這仍然是O(n)時間,對吧?這爲什麼這麼快?
t = linspace(-2*pi,2*pi,100000);
fd = 1e3;
tau = 1e-6;
% Calculate arbitrary function using a loop
tic
for tind = 1:length(t)
tester(tind) = cos(2*pi*fd*t(tind))/(2*pi*fd.*t(tind));
end
toc
pause; disp('Press a key');
% Same calculation with logical indexing
tic
tester2 = cos(2*pi*fd.*t)./(2*pi*fd.*t);
toc
您的第一個循環代表了與第二個循環相同的更高層次的方法;即腳本看起來並不是最優化的。 – ThomasRS 2011-04-08 01:02:25
這證實了Matlab循環吸吮的事實,如果有任何使用矩陣的方法,應該避免像瘟疫一樣。 – Reinderien 2011-04-08 01:10:25
@Reinderien - 不,你錯了。循環中的問題是,tind從未被預分配。所以發生的每一次都是通過循環,數組tind必須在內存中重新分配。 – 2011-04-08 11:10:58