Is self-reference possible in MATLAB?

前端 未结 3 1053
臣服心动
臣服心动 2020-12-05 18:15

As noted here, functions in packages, as well as static methods in classes, still need to use a packagename.functionname syntax or import packagename.*

3条回答
  •  遥遥无期
    2020-12-05 18:48

    So... doesn't this require importthis to also be imported? Or is importthis a function you always have in your path?

    It seems hardly more complex to just paste an "import this" block with this at the top of each function, and then you don't have to worry about importthis being in your path. I tend to feel that reliance on path is dangerous.

    "Import This" block

    %% Import own package
    [~, pkgdir] = fileparts(fileparts(mfilename('fullpath')));
    import([pkgdir(2:end) '.*']);
    

    You can even put it in a try/catch block to make sure it's in a package directory, and decide what to do if it's not.

    %% Import own package
    try
        [~, pkgdir] = fileparts(fileparts(mfilename('fullpath'))); 
        import([pkgdir(2:end)'.*']);
    catch err
        if ~strcmp(err.identifier,'MATLAB:UndefinedFunction'), rethrow(err); end
    end
    

提交回复
热议问题