2
$\begingroup$

I want to solve a system of differential equations and each time I want to change two parameters. To prevent wrong result I want to clear every assignment after solving the equations in each iteration. I have a Do-loop with two iterator. The problem is that if I use Clear["Global`*"] then the outer iterator will not be accessible to the code inside the loop.

Here is an example:

Do[{Print[a]; Clear["Global`*"];}, {a, 1, 2}, {b, 1, 2}]

Result:

1

a

2

a

As you can see the iterator a is erased for the inner iterator b. How can I resolve this issue?

I expect the outer iterator to be printed each time. There are 4 iteration in total, so I expect to get:

1
1
2
2

I want both iterators, a and b, in spite of using Clear command to be accessible to the code inside loop. I want to clear everything after each iteration except iterators a and b.

$\endgroup$
  • $\begingroup$ What would be your expected result? $\endgroup$ – Öskå Jul 1 '14 at 10:04
  • $\begingroup$ I edited the post. $\endgroup$ – MOON Jul 1 '14 at 10:09
  • $\begingroup$ Perhaps a description and removal of the actual symbol clash would be more effective than dropping the big one. Posting the offending code is often useful. $\endgroup$ – Yves Klett Jul 1 '14 at 10:27
2
$\begingroup$

How about this?

Do[{Print[a];
  Map[Clear, DeleteCases[Names["Global`*"], "a" | "b"]]},
 {a, 1, 2}, {b, 1, 2}]
$\endgroup$
  • 1
    $\begingroup$ That gives 1 1 2 2 as well as Do[{Print[a]; Quiet@ClearAll["Global`*"];}, {a, 1, 2}, {b, 1, 2}]. Apparently the OP desires 1 1 1 1. $\endgroup$ – Öskå Jul 1 '14 at 10:40
  • $\begingroup$ @Öskå I am sorry I was wrong. This answer is what I needed. $\endgroup$ – MOON Jul 1 '14 at 10:42
  • $\begingroup$ Without clearing a and b the result should be 1 1 2 2. $\endgroup$ – Chris Degnen Jul 1 '14 at 10:42
  • 1
    $\begingroup$ Ah, well, ClearAll is enough then :) $\endgroup$ – Öskå Jul 1 '14 at 10:42
  • $\begingroup$ As far as I know what I wrote in my first comment works ;o) $\endgroup$ – Öskå Jul 1 '14 at 10:45

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.