The next topic we will cover is scope in MATLAB. There are two types of scope: local and global. Scope is applied to variables and is important for fluidity when working with internal functions and functions from different scripts. Global scope for a variable means it can be accessed anywhere in the script, where local scope variables are only accessible in certain parts of a MATLAB script, for example, inside of functions. Let’s take a look at some examples of this.
matlab
x = 5;
out = scopeFunc(1); % output: 4
disp(x) % output: 5
function y = scopeFunc(z)
x = 3;
y = z + x;
end
In the code example, it starts off by defining a global variable x as 5. Then, the function ‘scopeFunc()’ is called and the output is stored in the variable ‘out’. ‘scopeFunc()’ is defined at the bottom of the script as an internal function and what it does is take in one input, denoted z, defines a local variable, x, as 3, and then sets the output to the function as z + x. What is interesting is if z = 1 for the input, then the output is $ z+x=1+3=4 $ because of the local definition of x inside of the function. We can also see after the function call, ‘disp(x)’ is written and 5 is outputted, same as the global x’s value.
What is happening here is inside of the function, the local x = 3 is not accessible to outside of the function, and that is why when ‘disp(x)’ was written, 5 was outputted. I like to think of global and local variables as trees on landmasses. When a function is written, I imagine an island next to the mainland and on that island are some trees that each represent the variables defined within that function. That way they are separate from the main script, or main code.
Let’s work with the example above and see what happens if we move some parts of it around. Let’s start by removing the local definition of x inside of the function and see what happens.
matlab
x = 5;
out = scopeFunc(1);
disp(x) % output: 5
function y = scopeFunc(z)
y = z + x; % This line will error because x is not defined
end
If you ran the code above, you will see an error will be thrown for the line $ y=x+x $ because x is not defined inside of the function! So that means when working with functions, all needed variables must be passed into the function as an input or defined inside of the function. Now, what happens if we instead remove the initial global definition of x? Let’s try it!
matlab
out = scopeFunc(1); % output: 4
disp(x) % This line will error because x is not defined
function y = scopeFunc(z)
x = 3;
y = z + x;
end
After running the above code, we then see the function runs now and outputs the correct value, but now the ‘disp(x)’ throws an error because there is no global definition for x. Scope is a powerful tool to utilize in creating efficient functions!