Given a named function, how can I call this function, and not the subfunction of the same name?

3 次查看(过去 30 天)
My function is passed the name of a function (as a string). It just so happens that my function contains a subfunction of that name. I want to make sure I call the external function, instead of the subfunction. How can I achieve this?
E.g. save the following in test.m:
function test
feval(evalin('base', 'str2func(''help'')'), 'help');
end
function varargout = help(varargin)
error('Should not get here!');
[varargout{1:nargout}] = deal([]);
end
Then calling test gives:
>> test
Error using test>help (line 6)
Should not get here!
Error in test (line 2)
feval(evalin('base', 'str2func(''help'')'), 'help');
  1 个评论
Oliver Woodford
Oliver Woodford 2015-5-29
I would say what I'm seeing is unexpected behaviour. Also, putting
evalin('base', 'which(''help'')')
as the first line in the help subfunction gives:
C:\....\test.m (help) % Subfunction of test
which is unexpected too.

请先登录,再进行评论。

采纳的回答

Titus Edelhofer
Titus Edelhofer 2015-5-29
Oliver,
what about this:
feval(evalin('base', '@(x) help(x)'), 'help')
This works fine. And as you noted yourself, using {:} you can expand the input variable as cell array.
Titus

更多回答(2 个)

Philip Borghesani
Philip Borghesani 2015-5-29
编辑:Philip Borghesani 2015-5-29
There is a much simpler solution to this:
function fh=test
fh=str2func('@(x) help(x)');
fh('help')
end
...
str2func isolates any anonymous function created from the surrounding environment see Loren's Blog
  1 个评论
Oliver Woodford
Oliver Woodford 2015-5-30
Nice! Thanks, Phil. I find it bizarre that str2func finds a different function depending on whether you use the anonymous function syntax or just the function name, though.

请先登录,再进行评论。


Titus Edelhofer
Titus Edelhofer 2015-5-29
Hi Oliver,
although this is not an answer to your question it might help anyway: this is one of the reasons to use function handles instead of strings denoting functions. The big advantage of a function handle is, that the function is determined in the moment the function handle in contrast to strings, where in the moment of evaluation the dispatching happens.
If you pass @help instead of 'help' to your function as input, you are sure, that the correct function is used.
Titus
  5 个评论
Oliver Woodford
Oliver Woodford 2015-5-29
编辑:Oliver Woodford 2015-5-29
The unlikely function name thing is a workaround which I can use. I'm hoping I won't need to, though. I can use the solution above :). Although the number of input arguments aren't known, I can put them in a cell array:
feval(evalin('base', '@(x) help(x{:})'), {'help'})
If you make it an answer I'll accept it.

请先登录,再进行评论。

类别

Help CenterFile Exchange 中查找有关 Startup and Shutdown 的更多信息

产品

Community Treasure Hunt

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

Start Hunting!

Translated by