TransWikia.com

Single expression containing the same pattern multiple times

Mathematica Asked on July 9, 2021

I have an expression like this Exp[-x^2]^(Log[a+3])*Sin[x]*y^(x)*Sin[Cos[b]], and I want to match the pattern base_^pwr_*Sin[arg_] s.t

Exp[-x^2]^(Log[a+3])*Sin[x]*y^(x)*Sin[Cos[b]] /. base_^pwr_*Sin[arg_]-> {base,pwr, arg}

will evaluate a list of lists where each sublist is one of the matched patters of the form {base,pwr, arg}.

However, when I run this code, I get
$$left{e^{-x^{2}} y^{x} sin [cos [b]], y^{x} log [3+a] sin [cos [b]], x y^{x} sin [cos [b]]right}$$
which doesn’t make any sense.

Ideally, I would like to get something like

{{e^{-x^{2}}, Log[3+a], x}, {y,x, Cos[b]}, {e^{-x^{2}}, Log[3+a], Cos[b]}, {y,x,x}}

Why am I getting this result and how can match check for multiple matchings of the same pattern in a single expression.

2 Answers

The is a case for ReplaceList:

expr = Exp[-x^2]^(Log[a + 3]) Sin[x] y^(x)  Sin[Cos[b]]; 

pattern = ___ base_^pwr_ Sin[arg_] :> {base, pwr, arg};

ReplaceList[expr, pattern]
{{E^-x^2, Log[3 + a], x}, 
 {E^-x^2, Log[3 + a], Cos[b]},
 {y, x, x},
 {y,  x, Cos[b]}}

This also works:

Map[Flatten] @ Tuples @ Values @
  GroupBy[List @@ expr, Head, ReplaceAll[ {Sin[x_] :> x, Power[a_, b_] :> {a, b}}]]

same result

And this:

DeleteDuplicates @ SequenceCases[List @@ expr, 
  {OrderlessPatternSequence[Power[a_, b_], Sin[c_], ___]} :> {a, b, c}, 
  Overlaps -> All]

same result

Correct answer by kglr on July 9, 2021

This is only a partial answer to explain the result that you see.

expr1 = Exp[-x^2]^(Log[a + 3])*Sin[x]*y^(x)*Sin[Cos[b]];

expr1 /. base_^pwr_*Sin[arg_] -> {base, pwr, arg}

(* {E^-x^2 y^x Sin[Cos[b]], y^x Log[3 + a] Sin[Cos[b]], x y^x Sin[Cos[b]]} *)

The pattern matched (E^(-x^2))^(Log[3+a])* Sin[x] and replaced it with the list {E^(-x^2), Log[3+a], x} This gave

{E^(-x^2), Log[3 + a], x}*y^x*Sin[Cos[b]]

(* {E^-x^2 y^x Sin[Cos[b]], y^x Log[3 + a] Sin[Cos[b]], x y^x Sin[Cos[b]]} *)

If you want it to continue until there are no more matches you would need to use ReplaceRepeated

expr1 //. base_^pwr_*Sin[arg_] -> {base, pwr, arg}

(* {{E y^x, -x^2 y^x, y^x Cos[b]}, {y Log[3 + a], x Log[3 + a], 
  Cos[b] Log[3 + a]}, {x y, x^2, x Cos[b]}} *)

I would guess that instead you might want to use Cases; however, you have not clearly defined what your desired result should be. And you should be looking at the FullForm of expr1

Answered by Bob Hanlon on July 9, 2021

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP