Reputation: 13015
I have several MATLAB scripts, e.g., fun1, fun2,...etc There can have dependency relationships among them. For instance, fun1 can call fun2 and fun2 can call fun3.
In order to remove unnecessary variables, should I put “clear all;” at the head of every functions.
function x1 = fun1(input1)
clear all;
...
Will this cause any potential issue, such as removing useful variables?
Upvotes: 0
Views: 3884
Reputation: 24127
Several answers so far have explained that using clear all
at the start of a function is not a helpful thing to do, as it will clear the input variables.
I'd just add that clear all
is often misused even in scripts. clear all
does more than just clear all variables from the current workspace; it also removes all functions, MEX files and any imported Java classes from memory (so many things will subsequently run more slowly if they need to be reloaded), reinitializes persistent variables, and removes any debug points.
If all you want to do is to clear variables, just use clear
(or clearvars
or clear variables
).
Upvotes: 2
Reputation: 12345
No, no no, 1000 times no.
The function
declaration will give you a clean workspace. When a function exits, the workspace (and all variables) will be cleaned up, except for globals and persistents.
Even in scripts, I discourage the use of indiscriminate clear all
statements. If you are in a position to need that feature, the function
keyword at the beginning of a file serves to clean up your workspace, without destroying anything else that you may happen to be working on.
Upvotes: 1
Reputation: 5823
Assuming fun1
, etc, are typical functions (e.g., not nested functions or anything), each function gets its own workspace. The only variables you'll have in this new function workspace are the input variables - so doing a clear all
as the first call in the function will clear the input variables. Your function wouldn't be able to operate on the inputs.
If you have a nested function, that nested function will be in the same workspace as the parent function - so a clear all
would obliterate the parents' variables, as well.
In general, only scripts should start out with clear all
, if you want your base workspace clean before running the script.
Upvotes: 1
Reputation: 5905
All clear all
will do in that context, is to remove your input variables. When you are within a function, the only variables that function sees are the variables passed into the function. So, you will find that to be not a particularly helpful pattern.
Upvotes: 5