       Re: Ask Mathematica to sub for a long expression

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

```Hi Aaron

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

In:= xpr1 = 2 Sqrt[a^2 + b^2 - 2*a*b*Cos[theta]]  (* an expression

then execute

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

Out:= 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:= 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:= 2 Sqrt[x^2 + y^2 - 2*x*y*Cos[theta]] /. expressionToBeReplaced
-> c

Out:= 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: 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