# Pattern Matching and Conditionals in Replacements

Given an expression of the form $c_1 v_1 - c_2 v_2$, I'd like to conditionally simplify this to $c_1 v - (c_2 - c_1) v_2$ if $c2 > c1 > 0$, and to $c_2 v + (c_1 - c_2)v_1$ if $c1 > c2 > 0$, where $v = v_1 - v_2$.

Any ideas?

• What have you tried? Are the $c_i$s and $v_j$s numeric quantities or symbolic ones that you are assuming things about? – Pillsy Apr 14 '17 at 0:44
• $c$'s are numeric, $v$'s are a value (I'm using vectors from xTensor package, but I don't think that should make a difference). – Miatrix Apr 14 '17 at 2:39

I think you are looking for a way to conditionally factor your equation:

Factor[First[c1 v1 - c2 v2 /. Solve[v == v1 - v2, Which[c2>c1>0, v1, c1>c2>0, v2]]]]


Testing it:

c2 = 3;
c1 = 2;

Factor[First[c1 v1 - c2 v2 /. Solve[v == v1 - v2, Which[c2>c1>0, v1, c1>c2>0, v2]]]]
(*FACTORED 2 v - v2*)
First[c1 v1 - c2 v2 /. Solve[v == v1 - v2, Which[c2>c1>0, v1, c1>c2>0, v2]]]
(*UNFACTORED -3 v2+2 (v+v2)*)

c2 = 2;
c1 = 3;

Factor[First[c1 v1 - c2 v2 /. Solve[v == v1 - v2, Which[c2>c1>0, v1, c1>c2>0, v2]]]]
(*FACTORED 2 v + v1 *)
First[c1 v1 - c2 v2 /. Solve[v == v1 - v2, Which[c2>c1>0, v1, c1>c2>0, v2]]]
(*UNFACTORED 3 v1 - 2 (-v + v1) *)

• It seems to work without Factor. And the result seems to have extra curly braces. – Goofy Apr 14 '17 at 0:55
• @Goofy good point, I forgot Solve returns a list of results, changed to extract using First – Peter Roberge Apr 14 '17 at 1:11