I'm pretty new to Mathematica. I was wondering is there any way to define the symbol $H_\pm(x,y) = f(x) \pm g(y)$ in one line, so that $H_-$ or $H_+$ can be called separately? Something like: H_-[1,2] = f[1] - g[2] and H_+[1,2] = f[1] + g[2] .
Asked
Active
Viewed 1,006 times
9
Skylar15
- 281
- 1
- 9
4 Answers
9
The most robust way I know of would be to use the built in Notation package and write something like
Needs["Notation´"]
Symbolize[H±] (* Be careful to use the Writing Assistant palette or other formatting guides s.t. the definition actually displays like you want it to and not Subscript or similar means *)
H±[x_, y_] := f[x] ± g[y] (* Same caveat about typesetting applies here as well *)
Then you get
In[1] := H±[1,2]
Out[1]:= f[1]±g[2]
In Mathematica it should look like this:
Graumagier
- 1,130
- 5
- 11
-
Thanks for the answer, but please see the edit in the question. – Skylar15 Nov 04 '15 at 20:09
-
Defining the symbols should work analogously to my answer, or do you want to define both of them in one expression? – Graumagier Nov 04 '15 at 20:23
-
Yeah I want to define both of them in one line. Because I have two really huge expression where things differ by plus-minus only, so I am looking for a compact way of writing both of them in one shot. – Skylar15 Nov 04 '15 at 20:26
7
Clear[H]
H[s_][x_, y_] :=
f[x] + Piecewise[{{-1, s === "-"}}, 1]*g[y] /; s === "+" || s === "-"
Examples:
{H["+"][x, y], H["-"][x, y]}
(* {f[x] + g[y], f[x] - g[y]} *)
Or
Clear[H]
H[s_][x_, y_] := f[x] + Sign[s]*g[y] /; Abs[s] === 1
Examples:
{H[1][x, y], H[-1][x, y]}
(* {f[x] + g[y], f[x] - g[y]} *)
Bob Hanlon
- 157,611
- 7
- 77
- 198
4
Here is a version that allows you to use $H_+$ and $H_-$ as requested:
(h:SubPlus|SubMinus)[H] ^:= With[
{hh=Replace[h, {SubPlus->Plus, SubMinus->Subtract}]},
hh[f[#1], g[#2]]&
]
A couple examples:
SubPlus[H][x, y]
SubMinus[H][2, 3]
f[x] + g[y]
f[2] - g[3]
This is how the above appears in a notebook:
Carl Woll
- 130,679
- 6
- 243
- 355
3
Here is a variation on @Bob Hanlon's answer that uses functions instead of strings or integers.
h[op_Symbol][x_, y_] := op[f[x], g[y]]
This will work on any function that takes two or more arguments: Plus, Subtract, Times, Divide, Union, Intersection, and so on.
{h[Plus][m, n], h[Subtract][m, n], h[Times][m, n]}
(* {f[m] + g[n], f[m] - g[n], f[m] g[n]} *)
It can be restricted to just Plus and Subtract with MemberQ.
k[op_Symbol /; MemberQ[{Plus, Subtract}, op]][x_, y_] := op[f[x], g[y]]
k will only work for Plus and Subtract. For example, Times will not evaluate.
{k[Plus][m, n], k[Subtract][m, n], k[Times][m, n]}
(* {f[m] + g[n], f[m] - g[n], k[Times][m, n]} *)
Hope this helps.
Edmund
- 42,267
- 3
- 51
- 143

