Reputation: 7121
I have m file (main.m
), and I have some variables that I have in this file.
In the end of the file, I wrote: clear all
I want to clear all the variables. so in the Matlab, I wrote: main
, in order to run the function.
When the function completes, I wrote in MATLAB console the name of one of the variables of main.m
.
For example, I wrote the variable: data
Surprisingly, the variable exists.
Why the expression clear all
doesn't delete it?
Thank you.
Upvotes: 0
Views: 5267
Reputation: 10580
Functions have their own variable scope. When you return from a function, all the local variables of the function are cleared and the variables and values that were present immediately before the function call are restored, the only difference being the return values of the function from which you just returned. You can easily follow this process by using MATLAB debugger, first make sure you have some variables defined in the first function, then step in to the second function (F11 at least in Linux version) and then step through the second function and finally step out the second function when you reach return
or end of the function, and you'll see that the local variables of the second function are cleared and the variables of the first function are restored.
This means that you cannot clear the workspace variables inside a function, at the least not by using clear all
, because inside a function clear all
only clears all variables inside its variable scope.
If you follow functional programming paradigm, usually you don't need to worry about workspace variables, because all that matters is the variables you create and modify in your own functions.
Upvotes: 4