1

I have this optimization problem that Mathematica solves correctly:

NMinimize[{x0^2 + x1^2 + x2^2, x0 - x1 + 2.0 x2 == 1.0, x0 + x1* + x2 == 0.0}, {x0, x1, x2}]

{0.17748, {x0 -> 0.0739345, x1 -> -0.205098, x2 -> 0.360484}}

My problem is I want x0, x1 and x2 to have these values from here on and I dont know how to do (set) this. For example, if i try to plot

Plot[x0 + x1*x + x2*x^2,{x,-1,1}]

it gives me an empty plot because it does not know what x0, x1,and x2 are.

Thanks for your help.

S

user89699
  • 151

1 Answers1

1

Give your solution a name, such as sol:

sol = NMinimize[{x0^2 + x1^2 + x2^2, x0 - x1 + 2.0 x2 == 1.0, 
                x0 + x1*+x2 == 0.0}, {x0, x1, x2}]

{0.17748, {x0 -> 0.0739345, x1 -> -0.205098, x2 -> 0.360484}}

You want to grab the second part of this solution namely sol[[2]]:

sol[[2]]

{x0 -> 0.0739345, x1 -> -0.205098, x2 -> 0.360484}

and substitute those values into your expression:

expr = x0 + x1*x + x2*x^2 /. sol[[2]];

Plot[expr, {x, -1, 1}]


(source: tri.org.au)

I want x0, x1 and x2 to have these values from here on

Although it is certainly possible to globally set x0 = blah, and x1 = bleh, ... you will quickly find yourself in trouble if you do so. It is a much better approach generally to leave x0, x1 and x2 as global unassigned variables, and to then create a special expression like expr above with these numeric values replaced, rather than globally setting the values of x0, x1, and x2.

wolfies
  • 5,174