How to write vectorized functions in MATLAB

后端 未结 4 1090
时光取名叫无心
时光取名叫无心 2021-02-09 16:41

I am just learning MATLAB and I find it hard to understand the performance factors of loops vs vectorized functions.

In my previous question: Nested for

4条回答
  •  逝去的感伤
    2021-02-09 17:37

    Could you explain to me that why is this code so effective compared to the simple nested loops? It has nested loops just like the other function.

    The problem with nested loops is not the nested loops themselves. It's the operations you perform inside.

    Each function call (especially to a non-built-in function) generates a little bit of overhead; more so if the function performs e.g. error checking that takes the same amount of time regardless of input size. Thus, if a function has only a 1 ms overhead, if you call it 1000 times, you will have wasted a second. If you can call it once to perform a vectorized calculation, you pay overhead only once.

    Furthermore, the JIT compiler (pdf) can help vectorize simple for-loops, where you, for example, only perform basic arithmetic operations. Thus, the loops with simple calculations in your post are sped up by a lot, while the loops calling median are not.

提交回复
热议问题