I've read this but I still don't understand why vectorized code is faster.
In for loops, I can use parfor to for parallel computation. If vectorized code is faster, does it means that it is automatically parallelized?
No. You're mixing two important concepts:
Consider for example a trivial case such as the following:
s=0;
for i=1:length(v),
s = s+v(i);
end
and
sum(v)
you should probably use tic and toc to time these two functions to convince yourself of the difference in runtime. There are about 10 similar commonly used functions that operate on vectors, examples are: bsxfun
, repmat
, length
, find
. Vectorization is a standard part of using MATLAB effectively. Until you can vectorize code effectively you're just a tourist in the world of MATLAB not a citizen.
While in many cases parfor can help a lot the type of loops that can be parfored for very large gains occur seldomly.