Kevin C
Kevin C

Reputation: 344

Mathematica: Plot the derivative of a piecewise function

I'm trying to plot the derivative of a mollifier function in Mathematica. It differentiates the function OK, and can plot the function using %, but I would like to be able to plot by assigning the derivative to be a function f[t_], then Plot[ f[t] , {t,-1,1} ].

I'm not sure how to solve the error that comes up.

The Mathematica code is:

Clear[moll, f]

moll[x_] := 
Piecewise[ {  {E^(-1/(1 - x^2)), -1 < x < 1} , {0,x <= -1 || x >= 1}  } ]; (* Standard     mollifier *)

f[t_] := D[ moll[t] , t]

f[t]

Plot[%, {t, -1, 1}] (* this line works *)

Plot[f[t], {t, -1, 1}] (* this line comes up with an error *)

Upvotes: 2

Views: 2265

Answers (3)

Mr.Wizard
Mr.Wizard

Reputation: 24336

With the given function you could use:

Plot[f[t], {t, -1, 1}, Evaluated -> True]

Evaluated -> True is to be preferred over Evaluate[f[t]].

Better is to follow nikie's advice and define f differently:

Block[{t},
  f[t_] = D[moll[t], t]
]

See Scoping in assigning a derivative for an explanation.

Upvotes: 2

Fred Klingener
Fred Klingener

Reputation: 146

The 'pickyness' of Plot comes from its Atttributes[Plot], which include HoldAll, so the unadorned f never gets evaluated. Force evaluation as ratatosk suggests.

Upvotes: 1

ratatosk
ratatosk

Reputation: 393

Try using Plot[Evaluate[f[t]], {t, -1, 1}]

Plot is a bit picky when it comes to user defined functions.

Upvotes: 6

Related Questions