On Matlab, when i am using a "for...end" loop, the indexing variable still exists in my workspace after the loop have been fully executed. I would like it to be automatically deleted, since its not relevant anymore outside of the loop and that it pollutes the workspace.
For example, in the following code, the variable "i", still exists after the execution of the loop. Since it should be a local variable, I would like it to be deleted automatically without me having to do it explicitely.
List = [1 2 3 4] ;
for i = List
fprintf('value = %i\n', i) ;
end
% "i" still exists, while its outside of its context
clear i; % I would like to avoid doing this everytime I exit a for..end
I know it is more of an aesthetic issue than a bug, but for an easier understanding of the results of my program, I would like those "temporary" variables to disappear when I exit their contexts.
So far, I only was able to reduce the number of those temporary variables by reusing them.
Edit:
It seems that there is no real solution to automatically remove those "temporary" variables. The closest ways to avoid having those variables are:
Avoiding loops
Make the loops in functions, the variables of the functions are local and won't get in the workspace.
If you REALLY want to make sure that some of your variables have limited scope, and you want to avoid calling clear
, you can use nested functions. Note that this may not help with readability, and it is more typing than calling clear
. However, it does make sure that the only variables in your main function workspace are the ones that you want/need to remain.
function doSomething
List = [1 2 3 4] ;
runLoopOnList()
%# some other code here
%# nested functions
function runLoopOnList
%# i, and any other variable defined here
%# will not appear in the workspace
%# in contrast, all variables in the workspace
%# are visible and can be changed by the nested function
%# If a nested function should assign a new important
%# variable in the main workspace, have it return
%# and output.
for i = List
fprintf('value = %i\n', i) ;
end
end %# nested function
end %# main function
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With