Main Content

functions

关于函数句柄的信息

说明

示例

s = functions(fh) 返回有关函数句柄的信息。此信息包括函数名称、类型和文件名。

functions 函数仅用于执行查询和调试操作。

注意

请勿以编程方式使用 functions,因为其行为可能在后续 MATLAB® 版本中更改。

示例

全部折叠

创建函数句柄并显示其信息。

fh = @cos;
s = functions(fh)
s = struct with fields:
    function: 'cos'
        type: 'simple'
        file: ''

创建匿名函数的函数句柄。显示其信息和所需变量的值。

创建函数 x2 + y 的句柄,并使用该句柄调用该函数。

y = 7;
fh = @(x)x.^2+y;
z = fh(2)
z =

    11

显示有关函数句柄的信息。

s = functions(fh)
s = 

            function: '@(x)x.^2+y'
                type: 'anonymous'
                file: ''
           workspace: {[1x1 struct]}
    within_file_path: '__base_function'

函数句柄包含必需的 y 值。

s.workspace{1}
ans = 

    y: 7

创建一个函数,该函数返回局部函数和嵌套函数的句柄。显示其信息。

在您的工作文件夹下的 functionsExample.m 文件中创建以下函数。该函数返回嵌套函数和局部函数的句柄。

function [hNest,hLocal] = functionsExample(v)

hNest = @nestFunction;
hLocal = @localFunction;

    function y = nestFunction(x)
        y = x + v;
    end

end

function y = localFunction(z)
y = z + 1;
end

调用该函数。

[hNest,hLocal] = functionsExample(13)
hNest = 

    @functionsExample/nestFunction


hLocal = 

    @localFunction

显示有关嵌套函数的句柄的信息。

s1 = functions(hNest)
s1 = 

     function: 'functionsExample/nestFunction'
         type: 'nested'
         file: 'C:\work\functionsExample.m'
    workspace: {[1x1 struct]}

显示有关局部函数的句柄的信息。

s2 = functions(hLocal)
s2 = 

     function: 'localFunction'
         type: 'scopedfunction'
         file: 'C:\work\functionsExample.m'
    parentage: {'localFunction'  'functionsExample'}

输入参数

全部折叠

查询的句柄,指定为函数句柄。

输出参数

全部折叠

有关函数句柄的信息,以结构体形式返回。结构体包含以下字段。

字段名称

字段说明

function

函数名称。如果与句柄相关联的函数是嵌套函数,则函数名称的形式为 main_function/nested_function

type

函数类型。例如,'simple''nested''scopedfunction''anonymous'

file

带有文件扩展名的函数的完整路径。

  • 如果函数是局部函数或嵌套函数,则 file 是主函数的完整路径。

  • 如果函数是内置 MATLAB 函数,则 file 是空字符数组 ('')。

  • 如果函数是匿名函数,并且是在命令行中或非 MATLAB 路径上的文件中定义,则 file 是空字符数组 ('')。

  • 如果函数是匿名函数并且在处于 MATLAB 路径上的文件中定义,则 file 是该文件的完整路径。

  • 如果您加载一个已保存的函数句柄,则 file 是空字符数组 ('')。

结构体还有其他字段, 具体取决于与该句柄相关联的函数类型。例如,局部函数有 parentage 字段,匿名函数有 workspace 字段。s 中的信息仅用于执行查询和调试操作。

扩展功能

版本历史记录

在 R2006a 之前推出