I have some problem with NMaximize.

The function NMaximize gives result like this

{f[xmax] ,{x -> xmax}}

I've read in various answers that I can isolate xmax by writing:


And I can get rid of the arrow, in order to obtain the numeric value of xmax, using /.

y /. NMaximize[f[x],x][[2]]

But then, when I type y, Mathematica doesn't give me back the numeric value of xmax, it just returns y again... What's wrong?

  • $\begingroup$ Did you try x /. NMaximize[f[x],x][[2]]? $\endgroup$ – Michael E2 May 24 '18 at 11:42
  • $\begingroup$ Nope, but I don't want to assign to x any value, I need x to be a variable $\endgroup$ – Cella May 24 '18 at 11:56
  • $\begingroup$ Use @MichaelE2 to insure I'm pinged about your response. -- I didn't assign any value to x; it's still a variable. Do you want something like x1 = x /. NMaximize[f[x],x][[2]]? Then the value is assigned to a symbol, namely x1, not x. (Did you actually try my previous suggestion? Please do.) $\endgroup$ – Michael E2 May 24 '18 at 12:03
  • $\begingroup$ Oooh, now I get it. Thank you, it worked $\endgroup$ – Cella May 24 '18 at 12:06

First example from the docs for NMaximize:

Find the global maximum of an unconstrained problem:

NMaximize[-x^4 - 3 x^2 + x, x]

{0.0825888, {x -> 0.16374}}

Extract the maximizing argument:

x /. Last[NMaximize[-x^4 - 3 x^2 + x, x]]


Note that ReplaceAll (/.) replaces the symbol x with the number 0.16374. It does not assign a value to x. If you want to store the value in another variable, use something like this:

x1 = x /. Last[NMaximize[-x^4 - 3 x^2 + x, x]]
  • $\begingroup$ There are also NArgMax and NMaxValue $\endgroup$ – ilian May 24 '18 at 13:34

you can write y=f[x] /. NMaximize[f[x],x][[2]] or use y=FindMaximum[f[x], x][[1]]


Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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