0

I want to create a function that when it is called clears the value of a parameter.

For example I want to keep the value of a parameter and then clear its valueby calling a function:

a = 1;
f[x_] :=
 {b = x;
Clear[x]}
f[a]

However calling f[a] gives an error Clear::ssym: 1 is not a symbol or a string as expected. How can I overcome this problem.

Nitra
  • 347
  • 1
  • 8
  • 2
    You will need to add a Hold Attribute to f. See http://mathematica.stackexchange.com/a/18737/121 and http://mathematica.stackexchange.com/q/17767/121. (I favor marking this question as a duplicate) – Mr.Wizard Nov 12 '16 at 14:44
  • Are you expecting anything to happen to a when the internal x is cleared? – Edmund Nov 12 '16 at 14:44
  • @Edmund From one perspective there is no internal x, as there would be with Module; at the time of evaluation it has already been replaced with 1. I suppose you know this but it might still confuse new users. – Mr.Wizard Nov 12 '16 at 14:46
  • a = 1; SetAttributes[f, HoldAll]; f[a_] := Clear[a]; – bill s Nov 12 '16 at 14:50
  • @Mr.Wizard Correct. I was asking that way to pry into the OP's expectation without getting into the nitty-gritties. – Edmund Nov 12 '16 at 15:37
  • Thank you very much for your answer @Mr.Wizard – Nitra Nov 12 '16 at 15:42
  • 2
    My first reaction is: you probably don't really want to do this. Can you explain why you want to proceed this way? – Alan Nov 12 '16 at 16:09
  • Agree with @Alan. Looks like an anti-pattern to me. Only very rarely you really need to do something like that, and usually that happens in advanced symbol-manipulation code. – Leonid Shifrin Nov 13 '16 at 19:36
  • @Alan. This was an example of what I really do. I solve a set of differential equations. All parameters have been defined and I get the solution. At one point I want to run a sensitivity analysis for a parameter. So I create a function which when it is called releases (clears) the numeric value of the parameter, then calls the ParametricNDsolver gives the results and then sets the parameter value at its original value again. – Nitra Dec 04 '16 at 13:24

0 Answers0