Matlab:arrayfun、cellfun、spfun 和 structfun 与简单的 for 循环 [英] Matlab: arrayfun, cellfun, spfun and structfun vs. simple for-loop

查看:73
本文介绍了Matlab:arrayfun、cellfun、spfun 和 structfun 与简单的 for 循环的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

哪个更好,使用所有 *fun 函数(arrayfuncellfunstructfunspfun) 还是简单地使用 for 循环?

Which one is better, using all the *fun functions (arrayfun, cellfun, structfun and spfun) or simply using for loop?

哪种方法可以提供更好的性能?就代码的可读性而言,哪些方法应该被视为更好的实践?

What method gives better performance and which methods should be considered better practice in terms of readability of the code?

推荐答案

这真的取决于你所说的性能" :)

It really depends on what you call 'performance' :)

如果您的意思是最短执行时间,那么有时 *fun 会更快(例如,cellfun('isempty', ...);(是的,字符串参数!)肯定比循环版本好).有时循环更快.如果您使用的是 Matlab 版本 <2006 年,默认使用 *fun 功能.如果您使用的是最近的任何内容,请默认使用循环.您仍然必须始终进行分析以找出哪个更快.

If you mean minimum execution time, well, sometimes *fun are faster (for example, cellfun('isempty', ...); (yes, string argument!) for sure beats the loop version). Sometimes a loop is faster. If you're on a Matlab version < 2006, go for the *fun functions by default. If you're on anything more recent, go for the loops by default. You'll still always have to profile to find out which one's faster.

正如 Amro 所指出的,如果您有一个能够进行 FP 算法的 GPU,以及支持 GpGPU 的最新版本的 Matlab,那么为 gpuArray 调用 arrayfun输入将被大规模并行化.但是,对于执行时间,不能做一般性的陈述;对于较小的数组,或绝对庞大的数组,将所有内容复制到 GPU 的开销可能会抵消并行化计算的任何好处,因此……分析确实是唯一可以确定的方法.

As noted by Amro, if you have a GPU capable of doing FP arithmetic, and a recent version of Matlab that supports GpGPU, then a call to arrayfun for gpuArray inputs will be massively-parallelized. However, no general statements can be made regardnig execution time; for smaller arrays, or absolutely humungous ones, the overhead of copying everything over to the GPU might undo any benefit of parallelizing the computations, so...profiling is really the only way to know for sure.

如果您的意思是最少的编码时间,那么我会说,只要操作简单,就*fun 而言,编码通常会更快.对于任何复杂的事情,通常最好进行循环.

If you mean minimum coding time, then I'd say it's usually faster to code in terms of *fun as long as the operations are simple. For anything complex it's usually better to go for the loop.

如果您的意思是最佳可读性,从而在专业环境中维护和实施更改所需的最少时间,当然,请继续循环.

If you mean optimum readability and thus minimum time required for maintenance and implementation of changes in a professional context, for sure, go for the loop.

目前,您的问题还没有一个明确的简单答案:)

At this point in time, there's not really a clear-cut simple answer to your question :)

这篇关于Matlab:arrayfun、cellfun、spfun 和 structfun 与简单的 for 循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆