如何确定代码是作为脚本还是函数执行?

sla*_*ton 11 debugging matlab

您可以在运行时确定执行的代码是作为函数还是脚本运行?如果是,推荐的方法是什么?

Kla*_*CPH 7

还有另一种方式.nargin(...)如果在脚本上调用它会出错.因此,以下简短功能应该满足您的要求:

function result = isFunction(functionHandle)
%
% functionHandle:   Can be a handle or string.
% result:           Returns true or false.

% Try nargin() to determine if handle is a script:
try    
    nargin(functionHandle);
    result = true;
catch exception
    % If exception is as below, it is a script.
    if (strcmp(exception.identifier, 'MATLAB:nargin:isScript'))    
        result = false;
    else
       % Else re-throw error:
       throw(exception);
    end
end
Run Code Online (Sandbox Code Playgroud)

它可能不是最漂亮的方式,但它有效.

问候


Eit*_*n T 6

+1是一个非常有趣的问题.

我能想出一种确定这一点的方法.解析执行的m文件本身并检查第一个非平凡的非注释行中的第一个单词.如果是function关键字,那么它就是一个函数文件.如果不是,那就是一个脚本.这是一个整洁的单行:

strcmp(textread([mfilename '.m'], '%s', 1, 'commentstyle', 'matlab'), 'function')
Run Code Online (Sandbox Code Playgroud)

如果是函数文件,则结果值应为1;如果是脚本,则结果值为0.

请记住,此代码需要从有问题的m文件运行,当然不是从单独的函数文件运行.如果你想制作一个通用函数(测试任何m文件的函数),只需传递所需的文件名字符串textread,如下所示:

function y = isfunction(x)
    y = strcmp(textread([x '.m'], '%s', 1, 'commentstyle', 'matlab'), 'function')
Run Code Online (Sandbox Code Playgroud)

为了使此功能更加健壮,您还可以添加错误处理代码,以在尝试之前验证m文件是否实际存在textread.