我正在尝试使用 Matlab 的 Coder 应用程序将 Matlab 中的递归函数转换为 C/C++ 代码。一般来说,Coder 会给出一个错误,指出不允许使用递归函数。但是,Matlab 帮助页面说,如果您遵循以下准则,您可以从递归函数生成代码:
“当您在用于代码生成的 MATLAB 代码中使用递归时,请遵循以下限制:”
我基本上了解条件,但我不知道如何让 Matlab 接受递归代码。我使用了 Matlab 中的一个示例:
function y = call_recursive()
n =35;
x = 10;
y = myrecursive(x,n);
end
function y = myrecursive(x,n)
coder.inline('never')
if x > 1
y = n + myrecursive(x-1,n-1);
else
y = n;
end
end
但我仍然收到“不允许递归函数”错误。我自己的代码的剥离版本是:%------------------------
function recursion_test()
recursive_fn();
end %recursive caller
%------------------------
%------------------------
function recursive_fn()
persistent mycount;
if isempty(mycount) %initialize the persistent variable
mycount = 0;
end
counter = 0;
while(counter<300)
mycount = mycount + 1;
if mycount<100 %some generic test condition
recursive_fn();
end
if mycount<200 %another generic test condition
recursive_fn();
end %if
counter = counter+1;
end
disp(counter);
end %recursive function
%------------------------
我的代码给出了与 Matlab 示例相同的错误。我的特定应用程序的递归次数不应超过 300 次……通常约为 50-90 次。请注意,上面的代码不能准确地跟踪递归,但我确实在实际代码中进行了跟踪。我可以将递归限制为 300 次,并强制编译器制作 300 个递归基本代码的拷贝(我不知道该怎么做……但现在这是一个不同的问题)。首先,我希望能够使用 Coder 应用程序使用上述函数生成 C/C++ 代码。那么,任何人都可以解释如何为上面的递归函数生成 C/C++ 代码。最低限度,我想调用时间递归,但理想情况下,我也想知道运行时递归。注意我已经浏览了 Matlab 的代码生成和递归帮助页面,并使用我最喜欢的搜索引擎搜索了解决方案,但是我无法找到一个清晰的分步过程。您的帮助将不胜感激。
最佳答案
Matlab Coder 为 Matlab 2020b 中的函数中的递归函数生成 C 代码,根据 Ryan Livingston 的评论,它可能适用于 Matlab 2016b 及更高版本,很可能不适用于 Matlab 2016a 及更早版本。它不适用于 Matlab 2015b。这里是 Matlab's recursion-related release notes这表明在 Matlab 2016b 中添加了递归代码生成。
如果您在为递归函数生成代码时遇到问题,Matlab Coder 应用程序将从以下递归 Matlab 代码生成 C 代码(请注意,该代码有效,但不应该做任何有用的事情,仅用于给出一个简单的示例递归)。您可以将其用作模板并从那里构建。
%------------------------
function recursion_test()
%clear all %<-uncomment this line to generate a conversion error
recursive_fn();
end %recursive caller
%------------------------
%------------------------
function recursive_fn()
persistent mycount;
if isempty(mycount) %initialize the persistent variable
mycount = 0;
end
counter = 0;
while(counter<300)
mycount = mycount + 1;
if mycount<100 %some generic test condition
recursive_fn();
end
if mycount<200 %another generic test condition
recursive_fn();
end %if
counter = counter+1;
end
disp(counter);
end %recursive function
%------------------------
关于c++ - 递归函数的 Matlab 代码生成,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64056080/