我可以使用什么语言功能或开箱即用的 hack 来完成 MATLAB 中的函数内联?烦人的是,a Google search for "matlab inline function"表明 MATLAB 的设计者认为“内联”意味着“从字符串构造匿名函数”(...wtf?)。
我问的原因是我正在编写一个需要快速运行的脚本,并且我遇到了很多情况,如果有一个辅助函数处理一些简单的加法或一些可以避免的东西会很好错误。但是,函数调用的成本(由 tic/toc
衡量)并不值得。我不相信 MATLAB 会缺少函数内联功能,因为那会阻碍分解!
最坏的情况,我可以使用 M4宏。
编辑: 作为对 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
最佳答案
具体答案:
关于您的示例用例,老实说,这让我觉得是一种微优化。这些加一运算当然不是阻碍代码快速运行的瓶颈,因此您应该专注于加快代码中进行大量计算的部分。
如果您只是出于审美原因(第一次尝试拼写!),或者因为您只是不喜欢跟踪额外的原因,那么您可以创建一个函数来处理它,就像在您的在我看来,例子是一个糟糕的选择,因为它只会让代码更难阅读和理解。我建议像这样简单地创建一个新变量:
windowOffset = windowWidth - 1;
lastWindowStartIdx = length(list) - windowOffset;
for windowStartIdx = 1:lastWindowStartIdx
display(list[windowStartIdx:windowStartIdx + windowOffset]);
end
一般答案:
关于您关于如何创建真实 inline functions 的更一般性问题在 MATLAB 中,就像在 C 或 C++ 中一样,我认为没有任何方法可以做到这一点。我想也许是一个 anonymous function可能符合要求,但在与 number of different types of functions in MATLAB 进行了一些简单的时序比较之后我发现匿名函数实际上比好的 ol'subfunction 慢用于简单的 +1 操作。
以下是我测试的示例函数:
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
如果匿名函数的行为像真正的内联函数,我会期望它们是最快的解决方案。
关于function - 有没有办法在 MATLAB 中执行函数内联?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5275140/