The Math Forum

Search All of the Math Forum:

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

Math Forum » Discussions » Software » comp.soft-sys.matlab

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

Advanced Search

Back to Topic List Back to Topic List Jump to Tree View Jump to Tree View   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
  Click to see the message monospaced in plain text Plain Text   Click to reply to this topic Reply

Loki <> wrote in message <>...
> 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.


Point your RSS reader here for a feed of the latest messages in this topic.

[Privacy Policy] [Terms of Use]

© The Math Forum at NCTM 1994-2018. All Rights Reserved.