MATLAB: Does MATLAB not allow a function name to be used as a variable name inside a function, even though the variable has been previously cleared

acceleratorclearingjitMATLABnaming

When I use a function name such as SIN as a variable name inside another function, I cannot access the SIN function even though I clear the variable previously. If the same steps are executed in a script or at the command line, then it gives the expected result and allows access to the function.
For example, the following function when executed results in an error.
function foo
sin = 5;
clear sin;
sin(pi)
The error obtained is:
??? Reference to a cleared variable sin.
Error in ==> foo at 4
sin(pi)
Expected Result: Even if a function name is used as a variable, the clearing of this variable from the workspace should once again allow access to the said function.

Best Answer

MATLAB 6.5 (R13) introduced significant changes in the way that MATLAB processes functions as opposed to scripts. These changes have improved the performance of MATLAB and have resulted in a substantial performance increase over earlier MATLAB versions for many applications.
The behavior you see is related to an optimization to speed up the execution of function files. The cost of this optimization was the need to enforce consistency of names in functions. Thus once the term 'sin' is used as a variable in a function, the term is "locked" as a variable name. Clearing this variable will not release the name, so that the corresponding function may be invoked.
A script however, is optimized differently than a function. When commands are executed in a script, or at the MATLAB command prompt, additional checks are performed at each line that allow for naming inconsistencies. Thus the same code will execute differently in a function and a script.
For example, the following three lines of code when executed at a MATLAB command prompt will return expected results.
sin = 5;
clear sin;
sin(pi)
In this code, 'sin' is initialized as a variable. The next line clears this variable and the term 'sin' is now associated with the MATLAB function SIN. The last line invokes this function with the argument 'pi'.
However, if the same code is contained in a function, as shown below then the execution of the function will return an error.
function foo
sin = 5;
clear sin;
sin(pi)
The error received is:
??? Reference to a cleared variable sin.
Error in ==> foo at 4
sin(pi)
Thus the function locks the term 'sin' to be a variable name even after the clearing of the variable.
The best suggestion is to discontinue the use of function names as variable names completely. However, in certain applications in which this is not possible, place the relevant code in a separate script and then invoke the script from the function. Thus when the function is executed, it will call the script, and the code inside the script will be executed line by line. However, the use of function names as variable names is strongly discouraged.