Loki <email@example.com> wrote in message <firstname.lastname@example.org>... > > Vecorized code is tremedously faster when compared to non-vectorized > code. > > Why is so? Reason lies only in CPU vector instructions that matlab > uses internally when execute vetorized code, or there are other > reasons?
The for-loop is generally (right or wrong) considered as slow not because it is a for loop but mainly because what is carried out inside the loop at each iteration.
There are two main things that MATLAB is different than compiled language 1) MATLAB data are internally coded in a complicated way to cover the management of all kind of data (typeless) 2) and function calling: the input/output arguments management, *sometime* data needs to be duplicated some where (not all the time) which is costly.
Because of that, accessing to single element and function calling are costly, and when it been carried out inside a loop, it slows down.
In the vectorized code, usually function calling is reduced to a single call, then accessing to matrix elements are done internally directly by its memory location as with C by the vectorized function (accumarray, histc, pointwise operation, ...). The is why it's generally faster.
The exception if ARRAYFUN and CELLFUN. They are faked vectorized code. Nothing is vectorized inside, and they are usually slower than the for-loop. Avoid using them when speed is critical.
In the later years, MATLAB has improved the JIT for accessing single element, and it short circuit some of the mechanisms I describe above in order to accelerate for-loop efficiency.