Function With varargin Argument That Can Be Compiled With codegen
6 views (last 30 days)
Show older comments
Bob Randall
on 16 Feb 2025
Commented: Bob Randall
on 20 Feb 2025
Hi Community,
What is the recipe to defining a function with a varargin argument that can be compiled with codegen?
Here is my example that doesn't work:
function test_functionArgument_varargin(varargin) %#codegen
assert( all(size(varargin)<= [1 , 3])); assert(isa(varargin, 'cell' ));
number = double(varargin{1});
string = varargin{2};
disp(number);
disp(string);
end
And this is an example of the function's call output (without compiling the function):
test_functionArgument_varargin(1,"AAAA",55)
Executing
codegen test_functionArgument_varargin
produces these errors that have a quite cryptic message at least to me:
Type Function Line Description
1 test_functionArgument_varargin 4 Varargin contains zero elements; element 1 is requested.
2 test_functionArgument_varargin 5 Varargin contains zero elements; element 2 is requested.
3 test_functionArgument_varargin 7 Undef. function or variable 'number'. The first assignment to a local variable determines its class.
4 test_functionArgument_varargin 8 Undefined function or variable 'string'. The first assignment to a local variable determines its class.
5 test_functionArgument_varargin 5 varargin and varargout are not supported here.
0 Comments
Accepted Answer
Walter Roberson
on 16 Feb 2025
Edited: Walter Roberson
on 17 Feb 2025
C has no native way of expressing optional arguments. The convention that has grown up in C is to arrange all of the optional parts into a single **void pointer and bundle pointers to values in a vector, and put a null pointer at the end of the vector. The code would cast the individual *void pointers to the appropriate type for each element. It would be hypothetically possible for codegen to go through the trouble of implementing this convention, but it is a bit awkward.
C++'s native way of expressing option arguments is to define multiple functions with the same name but different function signatures, and then at compile time to select the function definition that matches the function signature that the code was actually called with. Generating such code automatically from MATLAB code that uses varargin would not be simple.
More Answers (0)
See Also
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!