Take the 2-minute tour ×
Mathematica Stack Exchange is a question and answer site for users of Mathematica. It's 100% free, no registration required.

Unlike the function Clear, the function Unset does not work for string patterns. Given the name of a variable as a string, how can you unset the corresponding variable? Example:

Given:

x = 10;

trying to unset later:

Unset[Symbol["x"]]

results in

Unset::write: Tag Symbol in Symbol[x] is Protected. >>

Using With:

With[{var = Symbol["x"]}, Unset[var]]

results in

Unset::usraw: Cannot unset raw object 10. >>

Note that Clear["x"] is not an option, because it also removes all DownValues associated with x.

share|improve this question
2  
Dumb solution: ToExpression["Unset[" <> "x" <> "]"]. –  J. M. May 7 '13 at 12:27
add comment

1 Answer 1

up vote 11 down vote accepted

You can use the third argument of ToExpression to do this in a structured way:

ToExpression["x", InputForm, Unset]
share|improve this answer
    
That's a tricky solution! Thanks. –  sakra May 7 '13 at 13:00
1  
+1. I remember that you have a long history of using this construct, which I also use often. @sakra An alternative: Unset @@ ToHeldExpression["x"] –  Leonid Shifrin May 7 '13 at 16:47
    
Yes, it's useful when trying to do something with some symbols I get from Names["...*"]. The usual form one ends up with is ToExpression["x", InputForm, Function[expr, ..., {HoldAll}]], which is rather cumbersome. I did not know about ToHeldExpression. It might make some things simpler. –  Szabolcs May 7 '13 at 16:56
    
@Szabolcs ToHeldExpression is deprecated and undocumented, but I am sure it will stay. –  Leonid Shifrin May 7 '13 at 17:40
    
As noted here, ToHeldExpression[] was deprecated in version three. Still, it remains in the kernel, much like that other function Release[]... –  J. M. May 7 '13 at 20:51
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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