In the very general way I think the difference is actually throughput (latency) vs number of operations (complexity). If you would build a very dedicated ASIC for you algorithm you would have to n^3 operations. By vectorizing you are saying that some of these operations can be performed independently from each other in parallel. Matlab and current processors are more clever and can do certain operations in 'parallel' e.g. a 64bit processor could do 2-32bit summations 4-16bit etc.
Think of two algorithms both in O(n^3), a where each operation must be done complete independent (you can vectorize this algorithm) and b the other where they must be series (you can not vectorize it). Special hardware for each of those would both require n^3 operations. However, by using more hardware/gates for a you can finish the task in as quick as 1 clock cycle, while for b more hardware/gates does not help you and the task will take n^3 clock cycle.
EDIT:
Some code to illustrate the vectorization speed, although complexity (#operation) would not increase
clear variable;
Iterations = 100;
n = 2^20;
a = randi(100,[1,n]);
b = randi(100,[1,n]);
profile on;
for loop=1:Iterations
% Full vector approach
vector = a*b.';
% Partial vector approach
vector2 = sum(a.*b);
% Direct mathematical approach
serial = 0;
for id=1:n
serial = serial + a(id)*b(id);
end
end
profile viewer;
now technically matlab has some extra overhead per operation like checking if the operation makes sense etc, thus slowing for loop significantly. But in general this is just an example to illustrate a trend.
bsxfun
increases the speed while it is just afor-loop
written asc++
/mex
file. In such cases, I do not think vectorizing the code changes the complexity. – NKNO(n^3)
code should also beO(n^3)
, but with a much smaller prefactor. But here's the catch: this is only asymptotic behaviour (so you need very largen
to clearly see this), and there's usually a lot of fluff in your code (overhead from the point of view of your vectorization) that scales differently. So you really need hugen
and scaling across multiple orders of magnitude to say anything empirical about complexity. – Andras Deak