When I do these equivalent operations in MatLab, the first runs at 24.158371 seconds (the for loop). The second runs at 0.004976 seconds (logical indexing). What could MatLab possibly be doing that makes this run so much faster? This has to still be O(n) time, right?
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
The biggest cost in your first loop actually comes from dynamically resizing the array
tester. Each time through the loop, Matlab has to copy the existing array to a new location in memory with room for the extra element. So, that’s an O(n) operation for each iteration of the loop. If you pre-allocate the array, it will run much faster, e.g.On my system, I get 11.3 seconds for the original loop, 0.0013 seconds for the vectorized version and 0.010 seconds for the loop with the memory for
testerpreallocated.It’s worth mentioning that many other languages with resizable arrays allocate additional space in chunks proportional to the current size of the array, so the cost of building an array by appending one element at a time is only O(n log n), so this is a particular deficiency of Matlab.