How to select a specific .m function when two exist?

后端 未结 4 790
野的像风
野的像风 2021-01-17 19:13

First, here the way i\'m calling the function :

eval([functionName \'(\'\'stringArg\'\')\']); % functionName = \'someStringForTheFunctionName\'
4条回答
  •  北海茫月
    2021-01-17 19:45

    You can also create a function handle for the shadowed function. The problem is that the first function is higher on the matlab path, but you can circumvent that by (temporarily) changing the current directory.

    Although it is not nice imo to change that current directory (actually I'd rather never change it while executing code), it will solve the problem quite easily; especially if you use it in the configuration part of your function with a persistent function handle:

    function outputpars = myMainExecFunction(inputpars)
        % configuration
        persistent shadowfun;
        if isempty(shadowfun)
            funpath1 = 'C:\........\x\fun';
            funpath2 = 'C:\........\y\fun'; % Shadowed
    
            curcd = cd;
            cd(funpath2);
            shadowfun = @fun;
            cd(curcd); % and go back to the original cd
        end
    
        outputpars{1} = shadowfun(inputpars); % will use the shadowed function
        oupputpars{2} = fun(inputparts); % will use the function highest on the matlab path
    end
    

    This problem was also discussed here as a possible solution to this problem.

    I believe it actually is the only way to overload a builtin function outside the source directory of the overloading function (eg. you want to run your own sum.m in a directory other than where your sum.m is located.)

提交回复
热议问题