Search All of the Math Forum:

Views expressed in these public forums are not endorsed by NCTM or The Math Forum.

Notice: We are no longer accepting new posts, but the forums will continue to be readable.

Topic: Vectorized Code: *Why* it works..?
Replies: 3   Last Post: Apr 27, 2013 2:52 AM

 Messages: [ Previous | Next ]
 Bruno Luong Posts: 9,822 Registered: 7/26/08
Re: Vectorized Code: *Why* it works..?
Posted: Apr 27, 2013 2:52 AM

Loki <lokigtk@gmail.com> wrote in message <675mn8lu2ce1k7hkol2n2oh3m4k849p7u4@4ax.com>...
>
> 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.

Bruno

Date Subject Author
4/26/13 Loki
4/26/13 Nasser Abbasi
4/26/13 Nasser Abbasi
4/27/13 Bruno Luong