MathGroup Archive 2006

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

Search the Archive

Re: Ask Mathematica to sub for a long expression

  • To: mathgroup at
  • Subject: [mg71887] Re: Ask Mathematica to sub for a long expression
  • From: "Mark Westwood" <markc.westwood at>
  • Date: Sat, 2 Dec 2006 05:11:13 -0500 (EST)
  • References: <ekp4o4$2fq$>

Hi Aaron

The simple answer is that what you want to do is very easy in
Mathematica.  For example, define;

In[3]:= xpr1 = 2 Sqrt[a^2 + b^2 - 2*a*b*Cos[theta]]  (* an expression
involving your long expression *)

then execute

In[5]:= xpr1/.Sqrt[a^2 + b^2 - 2*a*b*Cos[theta]] -> c

Out[5]:= 2c

and now your fun begins.  Note the use of the /. which is a shorthand
notation for the ReplaceAll function.  Check out the on-line Help for
this.  As it stands this replacement rule is very inflexible, it will
only replace expressions which exactly match the given one.  What you
might want to do is replace expressions which match a more general
pattern.  For example, suppose you assign the expression to be replaced
to a variable, like this

In[12]:= expressionToBeReplaced = Sqrt[a_^2 + b_^2 -

(* note carefully the underscores appended to the variable names, which
transforms them into Patterns -- back to the Help system for further
info on this *)

and now you can try things like

In[14]:= 2 Sqrt[x^2 + y^2 - 2*x*y*Cos[theta]] /. expressionToBeReplaced
-> c

Out[14]:= 2c

Now the replacement works for any expression which has the same
structure as the one you are seeking to replace.  OK, over to you, post
again when you've mastered simple replacement rules and want more

Mark Westwood

aaronfude at wrote:
> Hi,
> Is it possible to ask Mathematica to replace a long expression, such as
> Sqrt[a^2+b^2-2*a*b*Cos[theta]] with "c", whenever it encounters that
> long expression?
> Thanks!
> Aaron Fude

  • Prev by Date: automation tool for documenting Mathematica calculations in PDF, HTML, and XHTML
  • Next by Date: Re: NIntegrate that upper limit is infinite
  • Previous by thread: Re: Ask Mathematica to sub for a long expression
  • Next by thread: Re: Ask Mathematica to sub for a long expression