Search code examples
matlabmatlab-compiler

How can I make MATLAB to ignore a function?


My problem is, even though there is a local variable called 'mu', when code runs the command

sqrt(mu)

Matlab tries to run the internal function called mu.

As far as I know this is not a normal behaviour. How can I make Matlab to use the local variable over it's internal function?

I plan to compile this code with deploy tool, therefore modifying matlab's internal function file is not suitable. Problem will occur in complied version.

Let me give more detail about the problem,

My main.m file calls function_a.m function. Function_a function runs another script named, constants . Constants.m file is not a function but a script, it only keeps some variables so when its loaded it fills workspace with those variables. It's format is,

const1=3; const2=5; mu=2;

Right after function_a runs constant.m, it tries to use the mu value. This is when matlab gives an error from it's internal mu function. It means that Matlab does not use local mu variable which was created by contants.m.

I used debugger to stop the code after running constant.m but before using mu in a command. Mu is actually in work space as it should be. While in debug mode, if I use the command sqrt(mu), it works as it should be. But when I let continue to run, when same command is written in function file, Matlab gives the error that shows it is trying to use the internal function.

How can I fix this?


Solution

  • First of all, there is no internal function named mu so I don't know what the confusion is there.

    The issue is likely happening because you have used mu as a function and then within the Constants script, you use it as a variable and MATLAB's static code analyzer gets confused so it goes with it's first usage as a function. This is the same issue that you'd encounter if you called load and tried to load a variable with the name of a function into the current workspace.

    But in general, to avoid issues like this, you should avoid using a script like Constants.m to populate the workspace of the calling function. This is because you end up with this ambiguity if the calling function's workspace contains functions or variables with the same name. A better approach would be to make Constants a function and have it return a struct which can then be used to access the constant variables

    function S = Constants
        S.const1 = 3;
        S.const2 = 5;
        S.mu = 2;
    end
    

    Then from within the calling function

    constants = Constants();
    
    % Use the constants
    value = constants.const1 + constants.mu;
    
    % Or assign them to "safe" variables that are specific to this calling function
    my_mu = constants.mu;
    

    In this way, mu from Constants.m doesn't always have to be called mu which leads to more robust and reusable code.