I need some advice on using the function FindMaximum as follows.

I find the function y(x) from a differential equation as below, and then for each c and each xMax I have different solutions y(x) and I evaluate Abs(y(x=xMax)).

test[a_, xMax_] := Module[{temp},
  temp = NDSolve[{y'[x] == c* y[x] Cos[x + y[x]], y[0] == 1}, 
    y, {x, 0, xMax}];

  (y /. temp)[[1]][xMax] // Abs (*Abs(y(x=xMax))*)

I fix xMax = 30 and narrow c from 0.2 to 0.5 and I want to find c that gives me the largest Abs(y(x=xMax)).

FindMaximum[{test[c, 30], 0.2 < c < 0.5}, {c, 0.3}]

But the code doesn't work. Errors appear likeenter image description here How can I resolve this.

  • 2
    $\begingroup$ Replace test[c_, xMax_] := Module[... with Clear[test];test[c_?NumericQ, xMax_] := Module[... and see if your problem goes away. That Clear[test] removes any cached old definition of test and the ?NumericQ forces evaluation to be done on numeric constants given to c instead of any possible symbolic evaluation of c without an assigned numeric constant value. $\endgroup$
    – Bill
    Commented Dec 11, 2019 at 2:23
  • 1
    $\begingroup$ Welcome to Mathematica.SE! I hope you will become a regular contributor. To get started, 1) take the introductory tour now, 2) when you see good questions and answers, vote them up by clicking the gray triangles, because the credibility of the system is based on the reputation gained by users sharing their knowledge, 3) remember to accept the answer, if any, that solves your problem, by clicking the checkmark sign, and 4) give help too, by answering questions in your areas of expertise. $\endgroup$
    – bbgodfrey
    Commented Dec 11, 2019 at 3:20
  • $\begingroup$ @Bill: Thank you. It works. $\endgroup$ Commented Dec 11, 2019 at 3:28

1 Answer 1


ParametricNDSolve is well suited for such problems. Try

test = ParametricNDSolveValue[{y'[x] == c*y[x] Cos[x + y[x]], y[0] == 1}, y[xMax], 
    {x, 0, xMax}, {c, xMax}]
FindMaximum[{Abs@test[c, 30], 0.2 < c < 0.5}, {c, 0.3}]
(* {0.480145, {c -> 0.2}} *)

By the way, the code in the question contains an error. Replace test[a_, xMax_] by test[c_, xMax_].

  • 1
    $\begingroup$ Thank you for your answer and very nice guidance above. $\endgroup$ Commented Dec 11, 2019 at 3:30

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.