Issues iterating over list of functions using str2func with codegen

2 views (last 30 days)
I want to use str2func to evaluate functions specified by strings in transpiled code. The basic setup is along the lines of
function output = computeFeatures(arbitraryData, funcList)
% arbitraryData = rand(100,1);
% funcList = {'max','min','mean','mode'};
% Pre-allocation
nFunc = length(funcList);
for iFunc = 1:nFunc
funcName = lower(funcList{iFunc});
funcHandle = str2func(funcName);
However, when I try to use codegen I get the following error,
"Nonconstant expression or empty matrix. This expression must be constant because its value determines the size or class of some expression."
I have not shown pre-allocation explicitly here, but I can if that is necessary.
Ultimately I would like to be able iterate over a list of functions (determined at compile time) with the same input and output data formats. The primary reason for this is to simplify development and avoid manually adding multiple new sections to my code base every time add a function to my "funcList".
All help is greatly appreciated.

Accepted Answer

Ryan Livingston
Ryan Livingston on 4 Apr 2023
Coder requires the input to str2func to be a constant name. Uncommenting the line
funcList = {'max','min','mean','mode'};
in your code allows me to call codegen
codegen computeFeatures -args 1:10
So you can always do something like this.
If you'd like to keep the list of operations elsewhere, you have 2 options: use a wrapper function or use coder.Constant to pass functions to codegen
function output = wrapper(arbitraryData)
funcList = {'max','min','mean','mode'};
output = wrapper(arbitraryData, funcList);
>> codegen wrapper -args 1:10
Alternatively, you can do codegen on computeFeatures directly with coder.Constant
funcList = {'max','min','mean','mode'};
codegen computeFeatures.m -args {1:10, coder.Constant(funcList)}
ans =
struct with fields:
MAX: 10
MIN: 1
MEAN: 5.5000

More Answers (0)


Community Treasure Hunt

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

Start Hunting!