MATLAB Answers

How do I call functions with names generated by str2func, varargin, and input argument blocks?

15 views (last 30 days)
I am building a piece of software which will require the user to write a few short functions of their own. The user will specify a tag and then write a few functions with names that must contain the tag. For example, they could choose tag = "happy" and then would be required to define functions named happy_template.m and happy_plot.m. Then a driver function calls each of these programs as it needs to. The problem is that I would like these user-defined functions to have defaults, and am using argument blocks to do this in my examples. I can't quite figure out how to make this work. Here's a minimal example.
Let the tag be demo_tag. I have created a first file called demo_tag.m.
function demo_tag(opts)
arguments
opts.x {mustBeNumeric} = linspace(0,pi);
end
plot(opts.x,sin(opts.x))
I then have a driver function:
function callTagFunction(tag,varargin)
myFunction=str2func(tag);
if nargin ==1
myFunction();
else
myFunction(varargin);
end
Then consider the following four calls:
>> demo_tag
>> demo_tag('x',1:10)
>> callTagFunction('demo_tag')
>> callTagFunction('demo_tag','x','1:10')
Error using demo_tag (line 1)
Invalid argument at position 1. A name is expected.
Error in callTagFunction (line 7)
myFunction(varargin);
The first three work correctly, but the fourth gives errors.

Accepted Answer

Stephen Cobeldick
Stephen Cobeldick on 30 Mar 2021
Edited: Stephen Cobeldick on 30 Mar 2021
function callTagFunction(tag,varargin)
myFunction=str2func(tag);
if nargin ==1
myFunction();
else
myFunction(varargin{:});
end % ^^^ comma-separated list
end % <- recommended
  2 Comments
Roy Goodman
Roy Goodman on 30 Mar 2021
Thanks for the answer and the further references! With your fix, the syntax works even if nargin == 1, so we can simplify the code further to:
function callTagFunction(tag,varargin)
myFunction=str2func(tag);
myFunction(varargin{:});
end
function demo_tag(opts)
arguments
opts.x {mustBeNumeric} = linspace(0,pi);
end
plot(opts.x,sin(opts.x))
end
And it even works with the new key/value syntax
>> callTagFunction('demo_tag',x=1:10)

Sign in to comment.

More Answers (0)

Community Treasure Hunt

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

Start Hunting!