Issues iterating over list of functions using str2func with codegen

2 次查看(过去 30 天)
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);
output.(upper(funcName))=funcHandle(arbitraryData);
end
end
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.

采纳的回答

Ryan Livingston
Ryan Livingston 2023-4-4
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);
end
>> 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)}
computeFeatures_mex(1:10,funcList)
ans =
struct with fields:
MAX: 10
MIN: 1
MEAN: 5.5000
MODE: 1

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 MATLAB Coder 的更多信息

产品

Community Treasure Hunt

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

Start Hunting!

Translated by