use*_*193 5 matlab anonymous-function undocumented-behavior
我有一个很长的匿名函数,我想知道是否可以修改帮助输出(很容易):
>> myfunc=@(x) x; %example anonymous function
>> help myfunc
myfunc is a variable of type function_handle.
Run Code Online (Sandbox Code Playgroud)
我知道长匿名函数可能是一个相当不寻常的东西 - 可以实现,也许只有函数句柄存在,可能只有未记录的函数?
编辑:评论者要求一个用例:我阅读了带有多个输出的anoynmous函数(这里有关于matlab艺术的Lorem),如
fmeanVar = @(x) deal(mean(x), var(x));
%a long example function to split a cell array containing 3D matrices into two cell arrays
myfunc=@(x,c) deal(cellfun(@(d) d(:,:,1:c:end),x),cellfun(@(d) d(:,:,setxor(1:c:end,1:end)),x));
Run Code Online (Sandbox Code Playgroud)
而且我想确保我记得第二个输出参数是什么,稍后及时,你知道......因为人类忘记了东西
问题是当你调用help它时重新读取文件.使用时创建匿名函数
f = @(x) x %Sample text
Run Code Online (Sandbox Code Playgroud)
然后它忽略了%Sample text,因此消失了.一种解决方案是将其转换为结构,其中一个字段是函数,另一个字段是帮助.比如像
fMeanVar.fct = @(x) [mean(x), var(x)];
fMeanVar.help = "Second output is the variance"
Run Code Online (Sandbox Code Playgroud)
因此,当您想要使用您调用的功能时
fMeanVar.fct([1,2,3,4])
Run Code Online (Sandbox Code Playgroud)
如果您忘记了使用情况,可以直接致电
fMeanVar.help
Run Code Online (Sandbox Code Playgroud)
您可以创建自己的匿名函数处理类,它将模仿此功能,仅遮蔽help此对象类型的函数.
我已经编写了下面的类,但是首先会显示用法,它只需要在你的路径上有一个类,并稍微调整你声明匿名函数的方式:
我们也可以覆盖subsref此类类型的函数,然后可以使用()语法直接调用函数句柄,而不是像Nicky的答案所建议的那样索引到结构中.
请注意,您必须传递句柄,而不是函数名称(即help(f)或f.help,help f或不help('f')).你必须完全遮蔽这个help功能以克服这个限制,我不会真的赞同!
用法
>> f = anon( @() disp( 'Hi!' ), 'This function displays "Hi!"' );
>> help( f )
Input is a value of type function_handle.
This function displays "Hi!"
>> f()
Hi!
>> f = anon( @(x) x + 10, 'Adds 10 to the input' );
>> help( f )
Input is a value of type function_handle.
Adds 10 to the input
>> f(15:17)
ans =
[ 25, 26, 27 ]
>> f.func = @(x) x + 15;
>> f.helpStr = 'Adds 15 to the input'
>> f(15:17)
ans =
[ 30 31 32 ]
Run Code Online (Sandbox Code Playgroud)
help如果未指定,则保留默认函数句柄
>> f = anon( @(x) x + 10 );
>> help( f )
Input is a value of type function_handle.
Run Code Online (Sandbox Code Playgroud)
班级代码
该类可以使用一些额外的输入检查等,但原则上工作!
classdef anon < handle
properties ( Access = public )
helpStr % String to display on help( obj )
func % Function handle (meant for anonymouse functions
end
methods
function obj = anon( func, helpStr )
assert( isa( func, 'function_handle' ) ); % Input check
obj.func = func;
if nargin > 1
obj.helpStr = helpStr; % Set help string
end
end
function help( obj )
h = help( obj.func ); % Normal behaviour.
if ~isempty( obj.helpStr )
% Custom string (does nothing if empty)
fprintf( '%s%s\n', h, obj.helpStr );
else
disp( h );
end
end
function varargout = subsref( obj, s )
% Need to override the subsref behaviour to enable default
% function calling behaviour!
switch s(1).type
case '()'
[varargout{1:nargout}] = obj.func( s(1).subs{:} );
otherwise
[varargout{1:nargout}] = builtin('subsref', obj, s);
end
end
end
end
Run Code Online (Sandbox Code Playgroud)