I have a calculation which at a certain point produces a conditional expression like
CE= (expression involving x) if 1<= x <= 3.
I want to extract the fact that the variable which is conditional is x, and that the bounds are 1 and 3.
Then I can continue the calculation by getting the values of the expression when x is 1 and when x is 3.
I guess I could do this by turning CE into a character string, searching for “if” and so on. But is there an easier (non-acrobatic) way?
Pattern matching is usually the answer to questions like this, but pattern matching is pretty literal in what you ask for, whether it will successfully match and what it gives you.
Asking how to get it to correctly identify the variable you want it to find that is within an unknown expression or even class of expressions and return to you is less literal than I can likely correctly answer with a first guess. Imagine if you were trying to write your string searching code to extract the correct variable name from my function if I knew the kinds of functions that I was going to use and you didn’t.
A little more directly, the condition is the second element of the expression ConditionalExpression[expr,cond]. You can extract it the same way you would with a list:
Thanks for all these. Hans Milton’s and Gianluca Gorni’s suggestions certainly work. I’m not sure of Bill Nelson’s. (In the meantime - not surprisingly - I’ve done what i needed in a completely different way.)
And here’s a bit:
If i write
e[x_] := ( Sqrt[1 - x^2] if - 1 <= x <= 1);
Then
e[.5] gives -1 + 0.866025 if <= 0.5
But if i write
f[x_] := ConditionalExpression[Sqrt[1 - x^2], -1 <= x <= 1];