Odds and ends
Single and two-variable examples:
out = FindMinimum[Sin[x], x]
out2 = FindMinimum[Sin[x] + Cos[y], {x, y}]
(*
{-1., {x -> -1.5708}}
{-2., {x -> -1.5708, y -> 3.14159}}
*)
Unflattened results (can always Flatten[]
them):
out /. Rule -> (#2 &)
out2 /. Rule -> (#2 &)
Apply[#2 &, out2, {2}] (* N.B. #2& @@@ -2. yields -2. *)
Extract[out2, {{1}, {2, All, 2}}]
FoldList[Values[#2] &, out2]
(*
{-1., {-1.5708}}
{-2., {-1.5708, 3.14159}}
...
*)
Flattened results (works on both one- and two-variable):
Flatten[out2 /. Rule -> (#2 &)] (* see previous set of examples *)
Cases[out2, _?NumericQ, 3](* or Cases[out2,_Real,3] for FindMinimum *)
Extract[out2, Join[{{1}}, Table[{2, j, 2}, {j, Length@Last[out2]}]]]
FoldList[Sequence @@ Values@#2 &, out2]
Level[out2, {-1}][[;; ;; 2]]
{#, ## & @@ (#2 & @@@ #2)} & @@ out2
(* {-2., -1.5708, 3.14159} *)
One-variable only:
Extract[out, {{1}, {2, 1, 2}}]
(* {-1., -1.5708} *)
See previous see for multivariable Extract
method. Often when working in a multivariable project, I define vars
to be the variables and use it so I don't have to type the variables out every time:
vars = {x, y};
out2 = FindMinimum[Sin[x] + Cos[y], vars];
Extract[out2, Join[{{1}}, Thread[{2, Range@Length@vars, 2}]]]
(* {-2., -1.5708, 3.14159} *)
Don't forget this unasked-for method of dealing with deconstructing the solution (I'd prefer to keep the independent variable solution component as replacement rules and just separate them from the optimum):
{ymin, xmin} = FindMinimum[Sin[x], x];
Update: Another way:
sol = Last@FindMinimum[f[x, y], {x, y}];
{f, x, y} /. sol (* or {x, y, f} /. sol *)
But I wouldn't use it if reevaluating f
is expensive. FindArgMin[f, vars]
returns a "solution" but not in the standard form of replacement rules. So if you want neither the value of f
nor a Rule
-form solution, use
FindArgMin[Sin[x], x]
FindArgMin[Sin[x] + Cos[y], {x, y}];
(* {-1.5708} <-- N.B. a 1-vector, not a scalar *)
(* {-1.5708, 3.14159} *)
And complementarily, for the function value without the argument values, there is
FindMinValue[f[x], x]