Services & Resources / Wolfram Forums
MathGroup Archive
*Archive Index
*Ask about this page
*Print this page
*Give us feedback
*Sign up for the Wolfram Insider

MathGroup Archive 2003

[Date Index] [Thread Index] [Author Index]

Search the Archive

Re: Re: extracting variables from an expression

  • To: mathgroup at
  • Subject: [mg44204] Re: [mg44135] Re: [mg44111] extracting variables from an expression
  • From: Andrzej Kozlowski <akoz at>
  • Date: Sun, 26 Oct 2003 00:41:58 -0400 (EDT)
  • Sender: owner-wri-mathgroup at

I forgot one more thing. You can further modify the definition below to 

Vars[expr_] := Union[Cases[expr,
     _Symbol?( !MemberQ[Attributes[#1], Protected] & ),

This will allow variables to be also Heads of expressions  e.g:

Vars[f[2] < 3 && f[2] > 1]


I think you probably do not need this, but I can imagine situations 
when this can be useful.It may be perhaps more likely that you would 
want f[2] rather than the head f to be the name of a variable, in which 
case you could use the definition:

Vars[expr_] := Union[Cases[expr, _Symbol?(! MemberQ[Attributes[#1],
Protected] &)[_] | _Symbol?(! MemberQ[Attributes[#1], Protected] &),

This now works with variables named f[1], f[2] etc as well as symbols, 

Vars[Vars[f[2] < Log[3] && f[2] > Log[a]]]

{a, f[2]}

Note that we have avoided getting Log[3] returned as a variable and at 
the same time managed to get a rather than Log[a] as another variable.

Andrzej Kozlowski
Yokohama, Japan

On Friday, October 24, 2003, at 05:24 PM, Andrzej Kozlowski wrote:

> You are quite right. I forgot about that. The function you need is
> Union. The correct code is:
> Vars[expr_] := Union[Cases[expr,
>     _Symbol?( !MemberQ[Attributes[#1], Protected] & ),
>     Infinity]]
> expr1 = a || b || c || (a && d);
> Vars[expr1]
> {a, b, c, d}
> On Friday, October 24, 2003, at 02:05 AM, Peter Schinko wrote:
>> Thank you very much for your help! The function works properly, but
>> there is
>> still one minor problem: the function isolates every single occurance
>> of a
>> variable, so for example:
>> expr1 = a || b || c || (a && d)
>> Vars[expr1]
>> will return
>> {a, b, c, a, d}
>> I need to remove all variables from the list that appear two times or
>> more,
>> so that I can construct a table with true and false to evaluate the
>> expression. I have tried to find such function, but I could not find
>> anything in "List Manipulation". Is there an easy way to do this
>> myself, or
>> is there such a function built in?
>> Thank you very much for your help!
>> Kind regards
>> Peter Schinko
>> University of Linz, Austria
> Andrzej Kozlowski
> Yokohama, Japan

  • Prev by Date: Re: New version, old bugs
  • Next by Date: Offending 2D-Axes
  • Previous by thread: Re: extracting variables from an expression
  • Next by thread: add this to the replacement example