Re: Ask Mathematica to sub for a long expression

• To: mathgroup at smc.vnet.net
• Subject: [mg71899] Re: Ask Mathematica to sub for a long expression
• From: "Philipp" <Philipp.M.O at gmail.com>
• Date: Sun, 3 Dec 2006 06:26:13 -0500 (EST)
• References: <ekp4o4\$2fq\$1@smc.vnet.net><ekrk8s\$s3q\$1@smc.vnet.net>

```Mark,

You are a bit condescending in your answer. Let's test your expertise.
How about;

In[1]:=  expressionToBeReplaced = Sqrt[a_^2 + b_^2 -
2*a_*b_*Cos[theta]];

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

still gives

Out[2]=  2*c + (x^2 + y^2 - 2*x*y*Cos[theta])^(3/2)

Cheers,

Philipp.

Mark Westwood wrote:
> 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 -
> 2*a_*b_*Cos[theta]]
>
> (* 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
> guidance.
>
> Regards
> Mark Westwood
>
> aaronfude at gmail.com 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: Reduction of Radicals
• Next by Date: Re: Re: Using subscripts in function-parameter names
• Previous by thread: Re: Re: Ask Mathematica to sub for a long expression
• Next by thread: Re: Ask Mathematica to sub for a long expression