Labfans是一个针对大学生、工程师和科研工作者的技术社区。 | 论坛首页 | 联系我们(Contact Us) |
![]() |
![]() |
#1 |
高级会员
注册日期: 2019-11-21
帖子: 3,006
声望力: 66 ![]() |
![]()
Which Way to Compute: cellfun or for-loop? 9
Posted by Loren Shure, September 25, 2019 Over a long number of years, people have asked whether it's better to use cellfun or a for-loop to perform certain computations. As with so many things in life, the correct answer here is "it depends". Let me give you a bit more insight so you can make good choices. Contents Function Handles If the function handle being called in cellfun takes a long time to evaluate, then the overhead from cellfun will be insignificant. So no big deal to use cellfun in this case. If the function being called in cellfun is very fast, such as issparse, you will likely be in the situation where the function call overhead dominates. Then use the function directly in a for-loop. If I know the number of inputs and outputs and the function I want to apply elementwise, I generally write an explicit loop. That might not be your preference, however. Remember, you can always put the code you wanted to write into comments! A Selected Set of Functions When cellfun was originally written, it could handle a fixed set of character arrays as the first input, with no additional flexibility. Over the years, the functionality has advanced. If you do use one of the sanctioned fix character arrays (and now scalar strings), however, you will get performance equivalent to the for-loop version. Here are the strings you can supply as the first input to cellfun and expect high performance (from the Backward Compatibility section in the doc for cellfun:
Do you use cellfun? When and how? With what first arguments? Let us know here. Get the MATLAB code Published with MATLAB® R2019b 更多... |
![]() |
![]() |