3
$\begingroup$

Consider the code defining two constants:

a=Cos[t]
b=Sin[t]

Suppose that we have another value in terms of Cos[t] and Sin[t], for example,

c=2*Cos[t]+Sin[t]^2

How to show the result of c in terms of a and b, that is, instead of the line above I'd like my computations being showed as

c=2*a+b^2

In other words, how to ask Mathematica to recognize Cos[t] as a?

$\endgroup$

3 Answers 3

4
$\begingroup$

One way to do something similar is to use rules instead of using equals.

rules = {Cos[t] -> a, Sin[t] -> b}
2 Cos[t]^2 + 3 Sin[t] //. rules

2 a^2 + 3 b
$\endgroup$
1
  • $\begingroup$ +1 Please read my answer as a comment to your answer :) $\endgroup$
    – eldo
    Commented Jul 16, 2014 at 1:15
2
$\begingroup$

One way to do that is as follow:

Unprotect[Cos, Sin];
Cos[t_] = a;
Sin[t_] = b;
c = 2*Cos[t] + Sin[t]^2

(*2 a + b^2*)

But be careful if you are going to use Cos or Sin to do calculations. they will return a and b.

$\endgroup$
1
  • $\begingroup$ I'll use only for symbolic computations to simplify some rotations. $\endgroup$
    – Sigur
    Commented Jul 16, 2014 at 1:06
0
$\begingroup$

My way is: (no guarantee to be the best way)

a = Cos[_];
rules = a -> Hold[a]
Cos[t] + 2 Cos[u] + 3 /. rules

It returns 3 + 3 Hold[a]. If you don't put a with Hold, Mathematica will evalute it, which we do not expect. You can also write a function to generate a list of rules when you need several such replaces. The benefit of writing rules = a -> Hold[a] (rather than rules = Cos[_] -> t, which t is another symbol to distinguish) is that you need not to care or to trace what is the definition of symbol a. Every time you use the rule, it simply means replacing the definition of a by a, namely a -> Hold[a].

(update) In order to increase the readability, using HoldForm is also a good choice.

a = Cos[_];
rules = a -> HoldForm[a]
sentence = Cos[t] + 2 Cos[u] + 3 /. rules

It returns 3 + 3 a.

sentence // FullForm

It returns Plus[3,Times[3,HoldForm[a]]].

So if you want to textually change "a" to a number or an another symbol:

In[]:= sentence
In[]:= sentence /. HoldForm[a] -> x
In[]:= sentence /. HoldForm[a] -> 15

Out[]= 3 + 3 a
Out[]= 3 + 3 x
Out[]= 48
$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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