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$
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$
  • $\begingroup$ Thank you for the answer! There was a very simple solution here. Surprising! $\endgroup$ – Smart Humanism Dec 30 '15 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$
  • $\begingroup$ Thank you for the answer! I also thought about this but I wanted to approach in a simpler way. $\endgroup$ – Smart Humanism Dec 30 '15 at 19:45

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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