Mathematica Stack Exchange is a question and answer site for users of Mathematica. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

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}.

share|improve this question
Change the definition of disc[]: disc[dt_?NumericQ] := (* stuff *). – J. M. Aug 14 '12 at 10:24
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... – J. M. Aug 14 '12 at 10:34
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. – Leonid Shifrin Aug 14 '12 at 11:11
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. – yohbs Aug 14 '12 at 11:26
Always try to post a running (and minimal) example of your problem. Otherwise you most probably will get right answers for the wrong problem – Dr. belisarius Aug 14 '12 at 12:03
up vote 9 down vote accepted

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

share|improve this answer

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

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