How can I delete/reset all the variables inside a loop without affecting those outside loop

107 views (last 30 days)
Syed
Syed on 10 Jun 2020
Answered: Walter Roberson on 10 Jun 2020
Hi all,
I have a lot of variables and I am running a simulation for 1000 number of times. Each 1000-run simulation is repeated by changing a variable.
Now I am using a lot of variables inside sim_cnt which are vectors and whose shapre change as 'n' changes.
Please see the code below.
How can I delete/clear all the variables inside the sim_cnt?
  1. I know the use of clear for certain variables, but I want to know if there is any generic statement that can clear all the variables' values within a for loop once the loop ends.
  2. I also dont want to use the function for the inner loop because in that case I will have to pass a very long list of variables to the function which will make the code very messy
for n = 1: 50
for sim_cnt = 1:1000
...
...
end
end

Answers (1)

Walter Roberson
Walter Roberson on 10 Jun 2020
I want to know if there is any generic statement that can clear all the variables' values within a for loop once the loop ends.
NO, there is not.
I am using a lot of variables inside sim_cnt which are vectors and whose shapre change as 'n' changes.
You should be pre-initializing all of the variables anyhow. Any variable that you already assign zeros or nan or whatever to, of proper length according to the current n, is already properly set up to not need to be cleared. Any variable whose previous value would interfer with use in the new iteration (such as because it is potentially the wrong size) should be initialized because it is inefficient to grow variables dynamically.
.. But if you really need to do this for some reason, adopt a naming convention for the variables inside the loop, and use clearvars with either the * wildcard or the -regexp option.

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!