I defined a function that I call disc which I want to minimize later. The function is defined as

disc[dt_]:=Total[(Log[vDat] - Log[(x'[tDat -dt] /. nsol)])^2]

and it quantifies the discrepancy between measured data (the time series {tDat,vDat}) and the solution to a differential equation that was obtained with NDSolve.

My problem is that this function works great sometimes:


but fails in other applications:

Another graph

I tried hard to get to the bottom of this, but I just can't understand what's wrong. Suggestions?

Clarification: disc[1] returns a number and not a {number}.

  • $\begingroup$ Change the definition of disc[]: disc[dt_?NumericQ] := (* stuff *). $\endgroup$ Aug 14, 2012 at 10:24
  • 2
    $\begingroup$ Yes, I was thinking of something else, so I removed that section. Unfortunately, I don't think we can be more helpful unless you at least show us your tDat, vDat, and nsol... $\endgroup$ Aug 14, 2012 at 10:34
  • 2
    $\begingroup$ A general remark is that defining functions which implicitly depend on global variables is, for most cases, a recipe for disaster. It may be also the case for your function. Check this answer for more details. $\endgroup$ Aug 14, 2012 at 11:11
  • 1
    $\begingroup$ Thanks for this remark. I know that, and my function is actually disc[sol_,dt_] and I have to give it the interpolating function too. I omitted that in the post for clarity. $\endgroup$
    – yohbs
    Aug 14, 2012 at 11:26
  • 2
    $\begingroup$ Always try to post a running (and minimal) example of your problem. Otherwise you most probably will get right answers for the wrong problem $\endgroup$ Aug 14, 2012 at 12:03

1 Answer 1


I think the problem is that you use the same variable symbol for the function returned by NDSolve and for the functions Plot and FindMinimum.

Here is a simplified example I tried. This is just an example equation from the documentation:

nsol = First@NDSolve[{x'[t] == x[t] Cos[t + x[t]], x[0] == 1}, x, {t, 0, 30}]

Here is a minimal definition of disc that demonstrates the problem:

disc[dt_] := x'[dt] /. nsol

Using the variable t the functions Plot and FindMinimum work fine: screenshot1
But using the variable x (the same name as the function solved for by NDSolve) I get similar problems to what you got: enter image description here


Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.