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

21 visualizaciones (últimos 30 días)
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.

Respuesta aceptada

Stephen23
Stephen23 el 30 de Mzo. de 2021
Editada: Stephen23 el 30 de Mzo. de 2021
function callTagFunction(tag,varargin)
myFunction=str2func(tag);
if nargin ==1
myFunction();
else
myFunction(varargin{:});
end % ^^^ comma-separated list
end % <- recommended
  2 comentarios
Stephen23
Stephen23 el 30 de Mzo. de 2021
Tested:
demo_tag
demo_tag('x',1:10)
callTagFunction('demo_tag')
callTagFunction('demo_tag','x',1:10) % no problem!
function callTagFunction(tag,varargin)
myFunction=str2func(tag);
if nargin ==1
myFunction();
else
myFunction(varargin{:});
end % ^^^ comma-separated list
end
function demo_tag(opts)
arguments
opts.x {mustBeNumeric} = linspace(0,pi);
end
plot(opts.x,sin(opts.x))
end
Roy Goodman
Roy Goodman el 30 de Mzo. de 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)

Iniciar sesión para comentar.

Más respuestas (0)

Categorías

Más información sobre MATLAB en Help Center y File Exchange.

Community Treasure Hunt

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

Start Hunting!

Translated by