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

조회 수: 19 (최근 30일)
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.

채택된 답변

Stephen23
Stephen23 2021년 3월 30일
편집: Stephen23 2021년 3월 30일
function callTagFunction(tag,varargin)
myFunction=str2func(tag);
if nargin ==1
myFunction();
else
myFunction(varargin{:});
end % ^^^ comma-separated list
end % <- recommended
  댓글 수: 2
Stephen23
Stephen23 2021년 3월 30일
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 2021년 3월 30일
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)

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Methods에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by