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

12 ビュー (過去 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 Center および File ExchangeLoops and Conditional Statements についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by