4
$\begingroup$

I am researching how to extract a certain value from an expression by using a pattern mechanism without actually changing the original expression.

The paragraph above could be very ambiguous, so here is an example. The aim here is to extract the number 4 before t and assign it to Symbol j.

Clear["Global`*"]; n = 3 Cos[4 t + 2] (* 3 Cos[2 + 4 t] *) n = 3 Cos[4 t + 2] /. _ Cos[r_ t + _] :> (k = r) (* 4 *) k (* 4 *) n (* 4 *) 

But unfortunately, it assigns 4 to n as well. Even if I use ; after k = r, it assigns Null to n as you can see below.

Clear["Global`*"] n = 3 Cos[4 t + 2] (* 3 Cos[2 + 4 t] *) n = 3 Cos[4 t + 2] /. _ Cos[r_ t + _] :> (k = r;) k (* 4 *) n 

How to extract 4 and assign it to k without having the original expression changed?

$\endgroup$
0

2 Answers 2

6
$\begingroup$

Parenthesize:

In[4]:= (n = 3 Cos[4 t + 2]) /. _ Cos[r_ t + _] :> (k = r); In[5]:= {n, k} Out[5]= {3 Cos[2 + 4 t], 4} 

Equivalently, use full form:

In[8]:= n =.; k =. In[9]:= ReplaceAll[n = 3 Cos[4 t + 2], _ Cos[r_ t + _] :> (k = r)]; In[10]:= {n, k} Out[10]= {3 Cos[2 + 4 t], 4} 
$\endgroup$
1
  • $\begingroup$ Thank you for the answer! There was a very simple solution here. Surprising! $\endgroup$ Commented Dec 30, 2015 at 19:43
2
$\begingroup$

The construction is a little funny, but you could also use Cases:

Clear[n, k, t] k = First@Cases[n = 3 Cos[4 t + 2], Cos[r_ t + _] :> r, Infinity] n (* {4} *) (* 3 Cos[4 t + 2] *) 

I very much like replacement rules with side effects, but I think here it is a little strange. The nice thing about using Cases here is that you can strip off the First, and then k will be set to the list of matches (which would work for the more general case of there being more than one match).

$\endgroup$
1
  • $\begingroup$ Thank you for the answer! I also thought about this but I wanted to approach in a simpler way. $\endgroup$ Commented Dec 30, 2015 at 19:45

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.