# Question for function FindMaximum

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 like How can I resolve this.

• 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. – Bill Dec 11 '19 at 2:23
• 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. – bbgodfrey Dec 11 '19 at 3:20
• @Bill: Thank you. It works. – Đạt Lê Thành Dec 11 '19 at 3:28

ParametricNDSolve is well suited for such problems. Try
test = ParametricNDSolveValue[{y'[x] == c*y[x] Cos[x + y[x]], y[0] == 1}, y[xMax],

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