MATLAB爱好者论坛-LabFans.com

MATLAB爱好者论坛-LabFans.com (https://www.labfans.com/bbs/index.php)
-   资料存档 (https://www.labfans.com/bbs/forumdisplay.php?f=72)
-   -   有没有一种方法可以在MATLAB中执行函数内联? (https://www.labfans.com/bbs/showthread.php?t=26572)

poster 2019-12-14 20:13

有没有一种方法可以在MATLAB中执行函数内联?
 
我可以使用哪种语言功能或现成的hack来完成MATLAB中的函数内联?令人讨厌的是, [URL="http://www.google.com/search?q=matlab+inline+function"]谷歌搜索“ matlab内联函数”时[/URL]发现,MATLAB的设计师认为“内联”的意思是“从字符串中构造匿名函数”(... wtf?)。

我问的原因是我正在编写一个需要快速运行的脚本,并且遇到很多情况,最好有一个辅助函数来处理一些简单的加法或避免一次失误的事情。但是,函数调用的成本(以tic/toc衡量)是不值得的。我拒绝相信MATLAB缺少函数内联功能,因为那样会阻止分解!

最坏的情况是,我可以使用[URL="http://en.wikipedia.org/wiki/M4_%28computer_language%29"]M4[/URL]宏。

编辑:作为对eat的评论的回应,在这种情况下,我可能希望内联帮助器:

一方面,我需要在列表中所有宽度为windowWidth窗口上循环(是的,我知道):

lastWindowStartIdx = length(list) - windowWidth + 1; for windowStartIdx = 1:lastWindowStartIdx display(list[windowStartIdx:windowStartIdx+windowWidth-1]); %the window we're looking at end 能够排除那些棘手的,容易出错的windowWidth计算,将是一个很好的选择。例如:

lastWindowStartIdx = calcLastWindowStartIdx(length(list), windowWidth); for windowStartIdx = 1:lastWindowStartIdx display(list[windowStartIdx:calcWindowEndIdx(windowStartIdx, windowWidth)]); %the window we're looking at end

[B]回答:[/B]

[B]具体答案: [/B]

关于您的示例用例,老实说,这是一种微优化。这些加一运算当然不是阻止其快速运行的瓶颈,因此,您应该专注于加快执行大量计算的代码部分。

如果您只是出于美学考虑(第一次尝试就拼写了!),或者只是因为不想跟踪多余的原因而进行此更改,则创建一个函数来处理它(如您的示例中所示)我认为这是个错误的选择,因为这只会使代码更难阅读和理解。我建议简单地像这样创建一个新变量:

windowOffset = windowWidth - 1; lastWindowStartIdx = length(list) - windowOffset; for windowStartIdx = 1:lastWindowStartIdx display(list[windowStartIdx:windowStartIdx + windowOffset]); end [B]一般回答: [/B]

关于您关于如何像在C或C ++中那样在MATLAB中创建真正的[URL="http://en.wikipedia.org/wiki/Inline_function"]内联函数[/URL]的更一般性的问题,我认为没有任何方法可以做到这一点。我以为[URL="http://www.mathworks.com/help/techdoc/matlab_prog/f4-70115.html"]匿名函数[/URL]也许很合适,但是[URL="http://www.mathworks.com/help/techdoc/matlab_prog/f4-62416.html"]在MATLAB中[/URL]对[URL="http://www.mathworks.com/help/techdoc/matlab_prog/f4-62416.html"]许多不同类型的函数[/URL]进行了一些简单的时序比较之后,我发现对于一个简单的+1操作,匿名函数实际上要比好的ol' [URL="http://www.mathworks.com/help/techdoc/matlab_prog/f4-70666.html"]子函数[/URL]慢。

这是我测试的示例函数:

function parent_function add_one_anon = @(A) A+1; %# An anonymous function add_one_inline = inline('A+1'); %# An "inline" function function add_one_nest %# A nested function A = A+1; end %# Did the timing here ... end function A = add_one_sub(A) %# A subfunction A = A+1; end 我运行了这100,000次中的每一次,以从1开始的标量值递增,结果如下:

| Time (sec) ------------+------------ subfunction | 0.0507 anonymous | 0.0672 nested | 0.0932 inline | 14.7095 如果匿名函数像真正的内联函数那样工作,我希望它们是最快的解决方案。



[url=https://stackoverflow.com/questions/5275140]更多&回答...[/url]


所有时间均为北京时间。现在的时间是 09:16

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