Re: Defining function in loop
- To: mathgroup at smc.vnet.net
- Subject: [mg40424] Re: [mg40412] Defining function in loop
- From: Andrzej Kozlowski <akoz at mimuw.edu.pl>
- Date: Sat, 5 Apr 2003 03:57:25 -0500 (EST)
- Sender: owner-wri-mathgroup at wolfram.com
Use Map instead of Do: In[1]:= Clear[g] g[x_]:=0/;x<0 Map[(g[x_]:=#/;#-1¡Âx¡Â#)&,Range[3]]; g[x_]:=4/;x>3 In[5]:= Table[g[x],{x,-1,4,.5}] Out[5]= {0,0,1,1,1,2,2,3,3,4,4} The reason why your code does not work is that inside the Do loop the right hand side of g[x_] := i/;i-1<=x<=i is not evaluated so your i's do not acquire any numerical values. Replacing := by = also won't work because of the HoldAll attribute of Condition. On Friday, April 4, 2003, at 03:27 pm, Vadim Nagornyi wrote: > Hello, > I am definihg step-like function > > Clear[h] > h[x_] := 0/;x<0 > h[x_] := 1/;0<=x<=1 > h[x_] := 2/;1<=x<=2 > h[x_] := 3/;2<=x<=3 > h[x_] := 4/;x>3 > > It works fine: > > Table[h[x],{x,-1,4,.5}] > {0, 0, 1, 1, 1, 2, 2, 3, 3, 4, 4} > > As I may need more steps, I am trying to do the same in loop: > > Clear[g] > g[x_] := 0/;x<0 > Do[g[x_] := i/;i-1<=x<=i, {i,3}] > g[x_] := 4/;x>3 > > This time no luck: > > Table[g[x],{x,-1,4,.5}] > {0, 0, 1, 1, 1, 2, 2, 3, 3, 4, 4} > {0, 0, g[0.], g[0.5], g[1.], g[1.5], g[2.], g[2.5], g[3.], 4, 4} > > How to do this? > > Thanks. > Vadim. > > > Andrzej Kozlowski Yokohama, Japan http://www.mimuw.edu.pl/~akoz/ http://platon.c.u-tokyo.ac.jp/andrzej/