MATLAB: Does unexecuted code in a function still cause an “Undefined function or variable”

analyzercodeconditionaldebuggererrorf10f9MATLABmessagestep

I am getting the error "Undefined function or variable", but the function I am calling is defined and on my MATLAB path.
I am calling this function within a conditional block of another function. The conditional block is set up as follows:
function fun1()
if myCondition
fun2 = aValue
else
fun2()
end
end
When I execute "fun1", it goes into the else-block and then errors out on the line which calls "fun2".
I tried setting a breakpoint on this line and running "fun1" again. At this point, if I highlight the line "fun2()" and press F9, or copy and paste this line into my MATLAB command window, it runs successfully without an error. But if I press the buttons 'continue', 'step', or 'step in', I get the error "Undefined function or variable".
Why is this, and how can I make sure MATLAB finds the function which I have defined?

Best Answer

This is the expected behavior. You are getting an error when you call "fun2()" because of the earlier line which sets "fun2 = aValue". Before even running your code, you may notice that the line "fun2()" is underlined in orange. If you hover over this line, there is a warning message that says "The variable 'fun2' might be used before it is defined".
In a function, identifier names are statically resolved. Even though "fun2" is called out as a variable in a conditional branch which will never get executed during runtime, statically "fun2" gets classified as a variable. When you then call "fun2()" as a function in the else-block, "fun2" has already been classified as a variable. Because this variable has not yet been defined, you see the error message "Undefined function or variable".
If you executed the same conditional block in a script instead of inside a function, you would not receive the error message, because there would not be static name resolution. Similarly, this is why you can successfully run the line "fun2()" using F9 (evaluate expression) or from the command line. These are both runtime constructs, and so "fun2" is not statically classified as a variable.
The following are some potential workarounds:
1. Use different identifiers for the variable you define in the if-block, and the function you are calling in the else-block.
If you can avoid creating a variable with the same name as your function, this function will not get statically classified as a variable.
2. Use an "eval" command.
The "eval" command is a runtime construct, so it does not take into account the static name resolution from a function. You can use the "eval" command in the following manner:
eval('fun2')
For more details, please refer to the documentation for "eval":