4

I run into this problem occasionally, and I haven't found a way around it. It usually happens when I'm finding the root of an equation, and want to maximize/minimize/plot that root according to some parameter. So I try to wrap the the code in a module so it can all be executed with just an input number, but it won't work inside functions like Plot. For example:

f[din_] := Module[{d = din},
  sol = NDSolve[{y'[x] == y[x], y[0] == 1}, y[x], {x, 0, 10}];
  t1 = Flatten[FindRoot[y[x] - d /. sol, {x, 1}]];
  x /. t1
  ]
f[2]
f[2.5]
f[3]
Plot[f[x], {x, 2, 3}]

The calls to f with a number all work as expected, but the f in the Plot function seems to be evaluated with the symbol 'x' - or something and just gives a lot of error text.

Any way around this?

Looking around the forums I found some suggestions for similar problems - like making the definition like this:

 f[din_?NumericQ]:=

and I tried everything I could but nothing seems to make a difference. I'm using Mathematica 8.0

argentum2f
  • 4,842
  • 2
  • 25
  • 30

2 Answers2

1

The main fix is to take the sol = NDSolve[... out of the module. The module itself can also be simplified as shown:-

sol = NDSolve[{y'[x] == y[x], y[0] == 1}, y[x], {x, 0, 10}];

f[din_] := x /. FindRoot[y[x] - din /. sol, {x, 1}]

Plot[f[x], {x, 2, 3}]

enter image description here

Chris Degnen
  • 8,443
  • 2
  • 23
  • 40
0

Try :

f[din_?NumericQ] := Module[{LocalDummy, Localy, LocalSol},
  Localy = y /. NDSolve[{y'[LocalDummy] == y[LocalDummy], y[0] == 1}, y, {LocalDummy, 0, 10}][[1]];
  LocalSol = FindRoot[Localy[LocalDummy] - din == 0, {LocalDummy, 1}][[1, 2]] ]

plot

b.gatessucks
  • 1,242
  • 1
  • 15
  • 19