Consider this very simple program written in a script:
a = 5;b = 10;d = difference();function dif = difference() dif = a - b;end
When executed, this will immediately result in an exception saying Unrecognized function or variable 'a'.
This is where my question is. Why can't local functions read variables that are defiend outside it in the script? In the above example, I would want my function to have access to variables a and b. There are two ways to do this currently: either pass them as parameters or make them global. The latter of the two is not the way I prefer to code.
I have a habit of breaking my code into several local functions. This makes debugging easier and implements the benefits of modularity. (I don't want to make these functions global because their work is often limited to the script only and I do not want the command line to have access to them.) If I have several local functions requiring the same variables, I would want those functions to have access to the variables by default.
I know this is easy to achieve this in Java by declaring the variables in the scope of the class. Consider the following Java code:
public class Abc{ int a = 5; double b = 10.236; void function1(){ // <some code here> } void function2(){ // <some code here> }}
In the above example, methods function1 and function2 have access to variables a and b. Each of those functions can change the values of those variables, and that will get reflected across functions of the same object.
While Java and MATLAB are built for different purposes, I feel that this feature of Java should be implemented in MATLAB. When I declare some variables in a script outside the local functions, those variables should be available to the functions by default (without requiring me to pass them as parameters or make them global). In case a local function defines another variable with the same name as the one defined in the script, the variable in the script should be shadowed by the one in the function.
Best Answer