Comparing arrayfun and for loop

1 回表示 (過去 30 日間)
Daniel Shub
Daniel Shub 2013 年 4 月 21 日
Has anyone ever compared arrayfun and a for loop for speed? This is partially inspired by this question about multi threading and the typical question (like this one) where people think loops are slow. If arrayfun and a for loop hasn't been compared, what is the proper test?
The only advantage I can see for arrayfun is that it is compact, which in certain circumstances might lead to easier to maintain code. There is also the possibility that the JIT might handle it better (for example loops slow down when you turn the profiler on). The for loop to me seems generally easier to read and would be easier to transfer to a multithreaded parfor.

回答 (1 件)

Matt J
Matt J 2013 年 4 月 21 日
編集済み: Matt J 2013 年 4 月 21 日
As a search of the Newsgroup will show you, they've been compared many many times and are known to be similar in speed. So, yes, the advantage that arrayfun/cellfun/etc.. is meant to offer is compact syntax and I assume they are similarly parallelized.
  2 件のコメント
Daniel Shub
Daniel Shub 2013 年 4 月 21 日
So then when someone asks to do something without a loop, giving an arrayfun answer is "cheating"?
Matt J
Matt J 2013 年 4 月 21 日
Only if the purpose of avoiding the loop is speed-up. If compact syntax is the goal, that's what arrayfun is meant for.

サインインしてコメントする。

カテゴリ

Help Center および File ExchangeLoops and Conditional Statements についてさらに検索

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by