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?
Vectorization is a type of parallel processing. It enables more computer hardware to be devoted to performing the computation, so the computation is done faster.
No, vectorized code is not always faster. If the vectorization needs the creation of large temporary arrays, loops are often faster.
Vectorization is one of the core concepts of MATLAB. With one command it lets you process all elements of an array, avoiding loops and making your code more readable and efficient. For data stored in numerical arrays, most MATLAB functions are inherently vectorized.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With