Mathematica Stack Exchange is a question and answer site for users of Mathematica. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

Suppose I have two functions $h_1(x)$ and $h_2(x)$, for which we know their sum and their difference: $$ h_1(x)+h_2(x) = d(x) \qquad h_1(x)-h_2(x) = i f(x) $$

I have a complicated expression, in which I'd like to replace these sums and subtractions. In principle, I could just define

h1[x_]:= 1/2 (d[x] + I f[x])
h2[x_]:= 1/2 (d[x] - I f[x])

and use Simplify. However, this is not an option as I'd like to keep the $h_i(x)$ when they appear alone (i.e. not as a sum/subtraction). So I defined a function simp as follows:

simp[a_. (b_. h1[x_] + b_. h2[x_]) + e_.] := simp[2 a b d[x] + e]
simp[a_. (b_. h1[x_] - b_. h2[x_]) + e_.] := simp[2 a b I f[x] + e]

This works for the addition, but not for the subtraction, as can be seen with the test expressions:

simp[1/2 a h1[x] + 1/2 a h2[x]]
simp[1/2 a h1[x] - 1/2 a h2[x]]

Why is this? Any idea how I can solve it?

share|improve this question
up vote 3 down vote accepted

The problem is that the pattern -b_. h2[x_] doesn't match the expression -1/2 a h2[x].

The reason is that putting a minus sign in front of a symbol means Times[-1, symbol] whereas a negative number is atomic (i.e. it is not represented as a positive number multiplied by -1). So a pattern like -x_ will not match a negative number:

MatchQ[-2, -x_]
(* False *)

In your case the pattern looks like Times[-1, b_. h2[x_]] and the expression looks like Times[Rational[-1,2], a h2[x], so they don't match.

One way to proceed is to use a pattern with different factors in front of the two terms and a Condition that one is the negative of the other:

simp[a_. (b_. h1[x_] + c_. h2[x_]) + e_.] /; b == -c := simp[2 a b I f[x] + e]

simp[1/2 a h1[x] - 1/2 a h2[x]]
(* simp[I a f[x]] *)
share|improve this answer
Perfect! This works, thanks. – freddieknets Jun 14 '13 at 11:05

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

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