How can I implement recursion in code-generated Simulink models?

13 vues (au cours des 30 derniers jours)
Philipp Tempel
Philipp Tempel le 13 Juin 2015
Commenté : chef13 le 25 Août 2015
I am wanting to implement a recursive function call inside a "MATLAB Function" block in my Simulink model. However, it fails when I want to run in Rapid-Accelerator mode because recursive function calls are not allowed/supported in code-generation.
You can think of the function I am calling as listing a directory's content which should obviously recurse into child directories if there are any. The method being called is not implemented in the block itself but in an m-file on my userpath.
Is there a way to facilitate using recursive function calls inside a "MATLAB Function" block or do I have to design the block differently?

Réponses (2)

Andrew Schenk
Andrew Schenk le 15 Juin 2015
Modifié(e) : Andrew Schenk le 15 Juin 2015
As you are aware, recursion is not supported for Simulink Code Generation. An alternative algorithm design for this recursive directory list would be to use a while loop with a dynamic list of directories. An example is shown below, but note that this example needs some modifications to support code generation since Cell Arrays are not supported.
%the initial directory
directories = {'./'};
while numel(directories) > 0
%the current directory
currentDir = directories{end};
%the current directory listing
listing = dir(currentDir);
%remove the current directory listing
directories(end) = [];
for i=1:numel(listing)
if strcmp(listing(i).name, '.') || strcmp(listing(i).name, '..')
%don't add the . or .. to the list
disp(fullfile(currentDir, listing(i).name));
if listing(i).isdir
directories{end+1} = fullfile(currentDir, listing(i).name);

Philipp Tempel
Philipp Tempel le 1 Juil 2015
Thank you Andrew, for the exemplary recursive code.
I will have to have a closer look into incorporating the code you provided into my recursive function (unfortunately it's not a function simple as getting the directory contents).
Are there really no ways to using recursive functions with code generation?
  1 commentaire
chef13 le 25 Août 2015
I am also interested in recursive functions with code generation.

Connectez-vous pour commenter.


En savoir plus sur Simulink Coder dans Help Center et File Exchange

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by