Mathematica 9 is now available
Student Support Forum
-----
Student Support Forum: 'Define function with conditions' topicStudent Support Forum > General > "Define function with conditions"

< Previous CommentHelp | Reply To Comment | Reply To Topic
Author Comment/Response
Randy Silvers
10/20/99 7:21pm

>
>
> I would like to define a function with two variables, as follow:
>
> f[x_,y_]:= g[x,y] if x not equal to y
> f[x_,y_]:= h[x] if y=x
>
> I don't know how to do this, and would appreciate any help.
> Thanks in advance
> Robin

Robin,

I have two methods, the first of which is very concise, the second of which is great for defining functions over intervals.

IF is a function which returns the value of the second argument if the first argument, the test, is true, else it returns the value of the third argument. Thus, the following returns h[x] if x=y, and returns g[x,y] otherwise:

f[x_,y_]:=IF[x==y,h[x],g[x,y]]

Alternatively, use UnitStep. This is an indicator function which takes on the value 1 if the value is non-negative, and 0 otherwise. Thus, try:

f[x_,y_]:=UnitStep[x-y]*g[x,y]+UnitStep[y-x]*g[x,y]+UnitStep[x-y]*UnitStep[y-x]*(h[x]-2g[x,y])

Here, if x>y, then the first term is g[x,y], the second term is 0 (as y-x<0), and the third term is zero for the same reason. If x<y, then the first term is 0 (as x-y<0), the second term is g[x,y], and the third term is zero for the same reason as the first. If x=y, then x-y and y-x are non-negative, so each UnitStep in f evaluates to 1. Thus, we must subtract off the two g[x,y] that are added in the first terms.

UnitStep is really good for defining functions over intervals, such as max[f(x),g(x)] can be rewritten as f(x)*UnitStep[f(x)-g(x)]+g(x)*UnitStep[g(x)-f(x)]-f(x)*UnitStep[f(x)-g(x)]*UnitStep[g(x)-f(x)]

Randy

URL: ,

Subject (listing for 'Define function with conditions')
Author Date Posted
Define function with conditions Robin Quartier 09/15/99 12:22pm
Re: Define function with conditions Carl Woll 09/15/99 7:18pm
Re: Define function with conditions Paul Ferraro 10/14/99 3:33pm
Re: Define function with conditions Randy Silvers 10/20/99 7:21pm
< Previous CommentHelp | Reply To Comment | Reply To Topic