# How to clear all things inside a loop?

It happens to me a lot when I write a loop, I have to Clear all functions, variables, definitions and etc to be sure my calculations is done correctly. namely as a toy example:

a=1;
b=2;
Do[
Clear[fun1,fun2,fun3];
fun1[x_]:=a+bx+c;
fun2[x_]:=b+ax+c;
fun3=fun1[x]+fun2[x];
,{c,{1,4,10}}]


Usually I have a lot of things (similar to above funs) which must be cleared inside my loop. In fact there is a complicated algorithm inside the loop which has inner loops itself. I do one of these:

1-If I need to save loop data in a matrix for example using Reap and Sow I have to use Clear[all things that I want to be cleared] manually

2- If I export data loop at each stage using Export or Put I just write ClearAll["Global*"] at the first of my loop. However most of time 1 is the case and it's a very time-consuming to clear all things manually. So I look for a way for clearing all things inside loop without clearing things outside it. Or it is better to ask: how can I use ClearAll["Global*"] but exclude a few functions? Any idea?

• You'll have to give us example code, as simple as possible, for how the problem arises. It simply doesn't happen for most of us. There's something about Mathematica that you're fighting rather than using. Oct 15, 2021 at 11:28
• but they are about ~60 functions which I had to define respectively Oct 15, 2021 at 11:49
• Why are you doing it this way, going back around and redefining functions, using them , then clearing them in a loop, all just to change parameters? This is inefficient - you should define your functions once and use the arguments from the call-site to change the behaviour. For example, in your code you should have fun1[x_,c_]:=..., fun2[x_,c_]:=... defined once, instead of the loop and redefinitions. That way you can easily call fun3=Table[fun1[x,c]+fun2[x,c], {c,1,4,10}] Oct 15, 2021 at 12:06
• If you want to try again, I would point out that in your MWE, there is no need to Clear the previous definitions. It makes it harder to imagine a situation in which you would. Oct 15, 2021 at 13:00
• The comment of @flinty is very relevant. It is unconventional to define and clear definitions in a loop. If it needs to be done, then it is against the very idea of a function, module, etc. They should be re-usable not one time objects. Oct 15, 2021 at 13:59

Here's how I would write your example, in a way that "jibes" with Mathematica.

(* Define the functions in terms of parameters *)
fun1[a_, b_][c_][x_] := a + b x + c
fun2[a_, b_][c_][x_] := b + a x + c
fun3[a_, b_][c_][x_] := fun1[a, b][c][x] + fun2[a, b][c][x]

(* Specify the parameters' values *)
a = 1; b = 2; c = {1, 4, 10};

(* Rather than loop, map across c *)
Through[(fun3[a, b] /@ c)@x]

(* Result *)
{5 + 3 x, 11 + 3 x, 23 + 3 x}