Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Extracting an expression matching a pattern from a large expression

I have a Mathematica expression that contains a single square root, schematically

expr = a / (b + Sqrt[c]);

where a,b,c are large expressions. I would like to extract the expression under the sqrt, for instance by matching to a pattern, something like

Match[expr,Sqrt[x_]] // should return c

Is there an easy way to do this?

like image 471
Guy Gur-Ari Avatar asked Apr 15 '11 22:04

Guy Gur-Ari


2 Answers

Theoretically, this should work correctly:

extractSqrt = Cases[ToBoxes@#, SqrtBox@x_ :> ToExpression@x, Infinity] &;

extractSqrt[expr]
like image 80
Mr.Wizard Avatar answered Oct 11 '22 23:10

Mr.Wizard


If you are willing to change the assignment to expr, you can do this:

expr = Hold[a / (b + Sqrt[c])];

Cases[expr, HoldPattern @ Sqrt[x_] :> x, Infinity]

The Hold in the assignment statement prevents Mathematica from applying any simplifications to the expression. In this case, Sqrt[c] gets "simplified" into Power[c,Rational[1,2]].

The HoldPattern is essential in the Cases expression to prevent the same simplification from happening to the pattern being matched.

like image 36
WReach Avatar answered Oct 11 '22 23:10

WReach