Labfans是一个针对大学生、工程师和科研工作者的技术社区。 论坛首页 | 联系我们(Contact Us)
MATLAB爱好者论坛-LabFans.com
返回   MATLAB爱好者论坛-LabFans.com > 其它 > 资料存档 > MATLAB技术文章
MATLAB技术文章 MATLAB Technical Articles From Mathworks
回复
 
主题工具 显示模式
旧 2019-11-23, 20:41   #1
poster
高级会员
 
注册日期: 2019-11-21
帖子: 3,006
声望力: 66
poster 正向着好的方向发展
默认 Which Way to Compute: cellfun or for-loop?

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:
  • "isempty"
  • "islogical"
  • "isreal"
  • "length"
  • "ndims"
  • "prodofsize"
  • "size"
  • "isclass"
There are some caveats with using these strings, including
  • cellfun does not call any overloaded versions of these functions
  • cellfun('isclass',C,classname) returns logical 1 (true) for each element of C that matches the classname argument. This syntax returns logical 0 (false) for objects that are a subclass of classname
Your Use of cellfun

Do you use cellfun? When and how? With what first arguments? Let us know here.


Get the MATLAB code

Published with MATLAB® R2019b


更多...
poster 当前离线   回复时引用此帖
回复


发帖规则
不可以发表新主题
不可以发表回复
不可以上传附件
不可以编辑自己的帖子

启用 BB 代码
论坛启用 表情符号
论坛启用 [IMG] 代码
论坛启用 HTML 代码



所有时间均为北京时间。现在的时间是 23:43


Powered by vBulletin
版权所有 ©2000 - 2025,Jelsoft Enterprises Ltd.